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

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


working example:

python code:

from flask import Flask, request, render_template, session, redirectimport numpy as npimport pandas as pdapp = 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__':    app.run(host='0.0.0.0')

html:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body>{% for table in tables %}            {{titles[loop.index]}}            {{ table|safe }}{% endfor %}</body></html>

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">    <title>Title</title></head><body style="">            <table border="1" class="dataframe data">  <thead>    <tr style="text-align: right;">      <th></th>      <th>A</th>      <th>B</th>      <th>C</th>    </tr>  </thead>  <tbody>    <tr>      <th>0</th>      <td>0</td>      <td>5</td>      <td>a</td>    </tr>    <tr>      <th>1</th>      <td>1</td>      <td>6</td>      <td>b</td>    </tr>    <tr>      <th>2</th>      <td>2</td>      <td>7</td>      <td>c--</td>    </tr>    <tr>      <th>3</th>      <td>3</td>      <td>8</td>      <td>d</td>    </tr>    <tr>      <th>4</th>      <td>4</td>      <td>9</td>      <td>e</td>    </tr>  </tbody></table></body></html>