Python 如何将 Pandas 数据框显示到现有的 Flask html 表中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52644035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:08:57  来源:igfitidea点击:

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

pythonpandasflaskpandas-datareader

提问by Motta

This may sound a noob question, but I'm stuck with it as Python is not one of my best languages.

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

I have a html page with a table inside it, and I would like to show a pandas dataframe in it. What is the best way to do it? Use pandasdataframe.to_html?

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

py

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

html

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

  <table id="table">

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

  </table>

</div>

回答by Nihal

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__':
    app.run(host='0.0.0.0')

html:

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

{{titles[loop.index]}}从 html 中删除行

if you inspect element on html

如果您检查 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>

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

如您所见,它在表格 html 中有 tbody 和 thead。所以你可以很容易地应用css。

回答by Chris Farr

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

HTML 代码:这将任何 DF 动态转换为可自定义的 HTML 表

<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 Code

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

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

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

回答by CSMaverick

# 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

或者当熊猫返回静态 HTML 文件时,您可以使用 Flask 将其呈现为页面

@app.route('/<string:filename>/')
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!

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

Update:

更新:

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)

Output

输出

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

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

回答by Biarys

For me using Jinja's for loop

对于我使用 Jinja 的 for 循环

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

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

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

{{ table|safe }}