Rendering pandas DataFrame to html on Flask

Viewed 4451

Can anyone give me some tips or links to investigate how to remedy a df.describe() in a web browser thru a flask app?

For example if I print(df.describe()) in IPython this comes thru in a nice format:

     kW
count  28219.000000
mean     134.723654
std       46.849081
min       24.300000
25%       91.300000
50%      135.900000
75%      168.600000
max      313.900000

But if I attempt this with a render template pass the data as string::

maxStatsStr = str(df.describe())

resp = make_response(render_template('table.html',
maxStatsStr=maxStatsStr))

return resp

To the front end HTML file with Jinja syntax:

<p>{{maxStatsStr}}</p>

This shows up in the browser

kW count 34880.000000 mean 79.687947 std 42.909287 min 12.200000 25% 38.800000 50% 73.400000 75% 113.200000 max 292.800000

Would a better method be creating like a table somehow, and using a for loop with Jinja to display the data? On the backend I just dont know how to prepare a df.describe() to be rendered as a table, like this below:

{% for table in tables %}
            {{ table|safe }}
{% endfor %}

FINAL CODE USED

statsInfoStr = df.describe().to_html()

resp = make_response(render_template('table.html',
maxDateStr=maxDateStr,

tables=[statsInfoStr], titles=df.describe().T))
return resp

table.html jinja to loop over data:

        <h2>Summary Statistics</h2>
        {% for table in tables %}
                    {{ table|safe }}
        {% endfor %}

    </body>
</html>
1 Answers

First, you can utilize the pd.DataFrame.to_html method to get the frame converted to html.

You might even use the Styling Guide to pretty it up before converting to html.

Then, you probably want to use the render_template_string function instead.

e.g.:

def some_flask_func(...):
    # ... your other codes ... #

    # If you just want to get the vanilla structure: 
    df_html = df.describe().to_html()

    # or, if you want to use Styler instead:
    df_html = df.describe().style.apply(some_style_func).render()

    # render directly from string:
    resp = make_response(render_template_string(df_html)
    return resp
Related