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.

Leave a Comment