Pandas Dataframe display on a webpage

flask, pandas, python

Solution

The following should work:

@app.route('/analysis/<filename>')
def analysis(filename):
    x = pd.DataFrame(np.random.randn(20, 5))
    return render_template("analysis.html", name=filename, data=x.to_html())
                                                                # ^^^^^^^^^

Check the documentation for additional options like CSS styling.

Additionally, you need to adjust your template like so:

{% extends "base.html" %}
{% block content %}
<h1>{{name}}</h1>
{{data | safe}}
{% endblock %}

in order to tell Jinja you're passing in markup. Thanks to @SeanVieira for the tip.

Problem

I am using Flask but this probably applies to a lot of similar frameworks. I construct a pandas Dataframe, e.g. ``` @app.route('/analysis/<filename>') def analysis(filename): x = pd.DataFrame(np.random.randn(20, 5)) return render_template("analysis.html", name=filename, data=x) ``` The template analysis.html looks like ``` {% extends "base.html" %} {% block content %} <h1>{{name}}</h1> {{data}} {% endblock %} ``` This works but the output looks horrible. It doesn't use linebreaks etc. I have played with `data.to_html()` and `data.to_string()` What's the easiest way to display a frame?

Original source