python - 如何将 Pandas 数据框显示到现有的 flask html 表中?

标签 python pandas flask pandas-datareader

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

我有一个 html 页面,里面有一个表格,我想在其中显示一个 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>

最佳答案

工作示例:

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>

如您所见,它在 html 表中有 tbody 和 thead。这样您就可以轻松地应用 css。

关于python - 如何将 Pandas 数据框显示到现有的 flask html 表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52644035/

相关文章:

python - 一种更有效的使用 if 条件的 pythonic 方式

python - 将日期范围行拆分为年(取消分组) - Python Pandas

python - 根据其他列的 groupby 为列设置值

python - 修改pandas dataframe的日期索引

javascript - 渲染新的图形数据会添加新图形,而不是替换现有图形

python - django "in"子句是否要求列表有两个值?

python - 在 "else" block 之后使用 "except" block 重要吗?

Python Pandas : Store multiple time series of variable length for multiple attributes for multiple users

python - Flask:不要重定向到 URL

python - 尝试使用Torch/PyTorch创建Docker镜像时出现MemoryError