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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With