首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将熊猫数据帧显示到现有的flask html表中?

如何将熊猫数据帧显示到现有的flask html表中?
EN

Stack Overflow用户
提问于 2018-10-04 18:06:57
回答 5查看 75.9K关注 0票数 48

这听起来可能是个菜鸟问题,但我被它卡住了,因为Python不是我最好的语言之一。

我有一个html页面,里面有一个表格,我想在其中显示一个熊猫数据帧。做这件事最好的方法是什么?使用pandasdataframe.to_html?

py

代码语言:javascript
复制
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

代码语言:javascript
复制
<div class="table_entrances" style="overflow-x: auto;">

  <table id="table">

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

  </table>

</div>
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2018-10-04 18:35:54

工作示例:

python代码:

代码语言:javascript
复制
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:

代码语言:javascript
复制
<!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>

或者使用

代码语言:javascript
复制
return render_template('simple.html',  tables=[df.to_html(classes='data', header="true")])

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

如果您在html上检查元素

代码语言:javascript
复制
<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>

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

票数 71
EN

Stack Overflow用户

发布于 2019-05-25 00:32:01

以防有人觉得这有帮助。我选择了另一种方法,因为我需要更多的定制,包括在执行操作的表中添加按钮的能力。我也真的不喜欢标准的表格格式,因为它非常丑陋。

代码语言:javascript
复制
...

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转换为可定制的HTML表

代码语言:javascript
复制
<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代码

代码语言:javascript
复制
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输出要好得多。

票数 32
EN

Stack Overflow用户

发布于 2018-10-04 18:11:18

代码语言:javascript
复制
# 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返回静态HTML文件时,您可以使用Flask将其呈现为页面

代码语言:javascript
复制
@app.route('/<string:filename>/')
def render_static(filename):
    return render_template('%s.html' % filename)

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

更新:

代码语言:javascript
复制
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 to HTML (由于样式的原因)

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52644035

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档