How to show a pandas dataframe into a existing flask html table?

working example:

python code:

from flask import Flask, request, render_template, session, redirect
import numpy as np
import pandas as pd

app = Flask(__name__)

df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                   'B': [5, 6, 7, 8, 9],
                   'C': ['a', 'b', 'c--', 'd', 'e']})

@app.route('/', methods=("POST", "GET"))
def html_table():

    return render_template('simple.html',  tables=[df.to_html(classes='data')], titles=df.columns.values)

if __name__ == '__main__':'')


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">

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

or else use

return render_template('simple.html',  tables=[df.to_html(classes='data', header="true")])

and remove {{titles[loop.index]}} line from html

if you inspect element on html

<html lang="en"><head>
    <meta charset="UTF-8">
<body style="">

            <table border="1" class="dataframe data">
    <tr style="text-align: right;">


as you can see it has tbody and thead with in table html. so you can easily apply css.

# Declare table
class SomeTable(Table):
    status = Col('Customer')
    city = Col('City')
    product_price = Col('Country')    

# Convert the pandas Dataframe into dictionary structure
output_dict = output.to_dict(orient='records')  

# Populate the table
table = SomeTable(output_dict)

return (table.__html__())

or as pandas return static HTML file you can render it as page using Flask

def render_static(filename):
    return render_template('%s.html' % filename)

It's the Idea of how we can do it in Flask. Hope you can understand this and let me know if it's not helping!


import pandas as pd

df = pd.DataFrame({'col1': ['abc', 'def', 'tre'],
                   'col2': ['foo', 'bar', 'stuff']})

from flask import Flask

app = Flask(__name__)

def hello_world():
    return df.to_html(header="true", table_id="table")

if __name__ == '__main__':'', debug=True)


But I'd go with Flask HTML feature rather than DataFrame to HTML (due to styling)

In case anyone finds this helpful. I have gone with an alternative because I needed more customization, including the ability to add buttons in the table that performed actions. I also really don't like the standard table formatting as it is very ugly IMHO.


df = pd.DataFrame({'Patient Name': ["Some name", "Another name"],
                       "Patient ID": [123, 456],
                       "Misc Data Point": [8, 53]})

# link_column is the column that I want to add a button to
return render_template("patient_list.html", column_names=df.columns.values, row_data=list(df.values.tolist()),
                           link_column="Patient ID", zip=zip)

HTML Code: This Dynamically Converts any DF into a customize-able HTML table

        {% for col in column_names %}
        {% endfor %}
    {% for row in row_data %}
        {% for col, row_ in zip(column_names, row) %}
        {% if col == link_column %}
            <button type="submit" value={{ row_ }} name="person_id" form="patient_form" class="patient_button">
                {{ row_ }}
        {% else %}
        {% endif %}
        {% endfor %}
    {% endfor %}


CSS Code

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;

tr:nth-child(even) {
    background-color: #dddddd;

It performs very well and it looks WAY better than the .to_html output.

For me using Jinja's for loop

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

didnt work as it simply printed each character 1 by 1. I simply had to use

{{ table|safe }}