如何将 pandas 数据框显示到现有烧瓶 html table 中?

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

这听起来可能是个菜鸟问题,但我还是坚持了下来,因为 Python 不是我最擅长的语言之一。

我有一个 html 页面,里面有一个 table,我想在其中显示一个 pandas 数据框。 最好的方法是什么?使用 pandasdataframe.to_html?

py

from flask import Flask;
import pandas as pd;
from pandas import DataFrame, read_csv;

file = r'C:\Users\myuser\Desktop\Test.csv'
df = pd.read_csv(file)
df.to_html(header="true", table_id="table")

html

<div class="table_entrances" style="overflow-x: auto;">

  <table id="table">

    <thead></thead> 
    <tr></tr>

  </table>

</div>
# 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__())

或作为 pandas return 静态 HTML 文件,您可以使用 Flask

将其呈现为页面
@app.route('/<string:filename>/')
def render_static(filename):
    return render_template('%s.html' % filename)

这是我们如何在 Flask 中实现它的想法。希望您能理解这一点,如果它没有帮助,请告诉我!

更新:

import pandas as pd

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


from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return df.to_html(header="true", table_id="table")

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

但我会使用 Flask HTML 功能而不是 DataFrame 来 HTML(由于样式)

工作示例:

python代码:

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__':
    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>

否则使用

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

并从 html

中删除 {{titles[loop.index]}}

如果您在 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>

如您所见,它在 table html 中有 tbody 和 thead。这样您就可以轻松申请 css.

对我来说,使用 Jinja for 循环

{% for table in tables %}
            {{titles[loop.index]}}
            {{ table|safe }}
{% endfor %}

没有用,因为它只是将每个字符 1 乘 1 地打印出来。我只需要使用

{{ table|safe }}

以防万一有人觉得这有帮助。我选择了一个替代方案,因为我需要更多自定义,包括在执行操作的 table 中添加按钮的能力。我也真的不喜欢标准 table 格式,因为恕我直言,它非常丑陋。

...

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 代码:这会将任何 DF 动态转换为 customize-able HTML table

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

</table>

CSS代码

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;
}

它表现得非常好,看起来比 .to_html 输出好得多。

对于那些正在寻找 simple/succinct 示例的人来说,将 Pandas df 转换为 Flask/Jinja table(这就是我结束这个问题的原因):

APP.PY -- 应用工厂:

## YOUR DF LOGIC HERE 

@app.route("/")
def home():
    return render_template('index.html' column_names=df.columns.values, row_data=list(df.values.tolist()), zip=zip)

您的静态模板(例如 index.html)

 <table>
        <thead>

          <tr>
            {% for col in column_names %}
            <th>
            
              {{col}}
             
            </th>
            {% endfor %}
          </tr>

        </thead>
        <tbody>
          {% for row in row_data %}
          <tr>
            {% for col, row_ in zip(column_names, row) %}
            <td>{{row_}}</td>
            {% endfor %}
          </tr>
          {% endfor %}

         
        </tbody>
  
      </table>