Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Dataframe display on a webpage

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?

like image 492
tschm Avatar asked Mar 04 '14 19:03

tschm


People also ask

How do I display pandas DataFrame in HTML?

Pandas in Python has the ability to convert Pandas DataFrame to a table in the HTML web page. pandas. DataFrame. to_html() method is used for render a Pandas DataFrame.

How do you embed a DataFrame in HTML?

To render a Pandas DataFrame to HTML Table, use pandas. DataFrame. to_html() method. The total DataFrame is converted to <table> html element, while the column names are wrapped under <thead> table head html element.

How do I display the whole pandas DataFrame?

Use pandas. Call pandas. set_option("display. max_rows", max_rows, "display. max_columns", max_cols) with both max_rows and max_cols as None to set the maximum number of rows and columns to display to unlimited, allowing the full DataFrame to be displayed when printed.

Can pandas read data directly from a Web URL?

Reading data-files into Pandas from from the web The simplest example of getting data from the web is where we load a csv file straight from the web instead of downloading it to our computer first. This is really easy because Pandas can take urls directly as well as local files. Pandas can also read excel files.


1 Answers

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.

like image 176
MattDMo Avatar answered Sep 20 '22 08:09

MattDMo