如何将 Pandas 数据框显示为 Flask-boostrap 表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39403529/
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-09-14 01:59:00  来源:igfitidea点击:

How to show a pandas dataframe as a flask-boostrap table?

pythonhtmlpython-3.xpandasflask

提问by tumbleweed

I would like to show a pandas dataframe as a boostrap-html table with flask, thus I tried the following:

我想将 Pandas 数据框显示为带有烧瓶的 boostrap-html 表,因此我尝试了以下操作:

The data (.csv table):

数据(.csv 表):

Name    Birth Month Origin  Age Gender
Carly   Jan Uk  10  F
Rachel  Sep UK  20  F
Nicky   Sep MEX 30  F
Wendy   Oct UK  40  F
Judith  Nov MEX 39  F

The python code (python_script.py):

蟒蛇代码(python_script.py):

from flask import *
import pandas as pd
app = Flask(__name__)

@app.route("/tables")
def show_tables():
    data = pd.read_csv('table.csv')
    data.set_index(['Name'], inplace=True)
    data.index.name=None
    females = data.loc[data.Gender=='f']
    return render_template('view.html',tables=[females.to_html(classes='female')],

    titles = ['na', 'Female surfers'])


if __name__ == "__main__":
    app.run(debug=True)

The templatesdirectory (view.html):

templates目录(view.html):

<!doctype html>
<title>Simple tables</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
  <h1>Surfer groups</h1>
  {% for table in tables %}
    <h2>{{titles[loop.index]}}</h2>
    {{ table|safe }}
  {% endfor %}
</div>

The boostrap style.css:

助推器style.css

body            { font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;}
a, h1, h2       { color: #377ba8; }
h1, h2          { margin: 0; }
h1              { border-bottom: 2px solid #eee; }
h2              { font-size: 1.2em; }

table.dataframe, .dataframe th, .dataframe td {
  border: none;
  border-bottom: 1px solid #C8C8C8;
  border-collapse: collapse;
  text-align:left;
  padding: 10px;
  margin-bottom: 40px;
  font-size: 0.9em;
}

.male th {
    background-color: #add8e6;
    color: white;
}

.female th {
    background-color: #77dd77;
    color: white;
}

tr:nth-child(odd)       { background-color:#eee; }
tr:nth-child(even)  { background-color:#fff; }

tr:hover            { background-color: #ffff99;}

So far, when I run my python_script.py:

到目前为止,当我运行我的python_script.py

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 123-221-151

I got two issues: a Not Found error and when I go to http://127.0.0.1:5000/tablesI got an builtins.KeyError KeyError: 'Name'. Any idea of how to show a pandas dataframe as a table with pandas and flask?.

我遇到了两个问题:一个 Not Found 错误,当我去的时候http://127.0.0.1:5000/tables我得到了一个builtins.KeyError KeyError: 'Name'. 知道如何将Pandas数据框显示为带有Pandas和烧瓶的表格吗?

回答by Nehal J Wani

The problem here is with the data.csvfile. When you do read_csv()on it:

这里的问题是data.csv文件。当你这样做read_csv()时:

In [45]: pd.read_csv("/tmp/a.csv")
Out[45]: 
  Name    Birth Month Origin  Age Gender
0                  Carly   Jan Uk  10  F
1                  Rachel  Sep UK  20  F
2                  Nicky   Sep MEX 30  F
3                  Wendy   Oct UK  40  F
4                  Judith  Nov MEX 39  F

In [46]: df = pd.read_csv("/tmp/a.csv")

In [47]: df.columns
Out[47]: Index([u'Name    Birth Month Origin  Age Gender'], dtype='object')

As you can see, there is only one column, instead of four, because it can't understand that 'Birth Month' is supposed to be one column. To fix this, you can open the file and change the first line to:

如您所见,只有一列,而不是四列,因为它无法理解“出生月份”应该是一列。要解决此问题,您可以打开文件并将第一行更改为:

"Name" "Birth Month" "Origin"  "Age" "Gender"

And, then while reading the csv:

然后,在阅读 csv 时:

In [62]: pd.read_csv("/tmp/a.csv", sep='\s+', quotechar='"')
Out[62]: 
     Name Birth Month Origin  Age Gender
0   Carly         Jan     Uk   10      F
1  Rachel         Sep     UK   20      F
2   Nicky         Sep    MEX   30      F
3   Wendy         Oct     UK   40      F
4  Judith         Nov    MEX   39      F

Or you could have also just changed Birth Monthto Birth_Month

或者您也可以更改Birth MonthBirth_Month

For the '404 Not Found' error, the problem is that you have not defined any route for '/'. So, (after editing the header of the csv) I would do something like:

对于“404 Not Found”错误,问题在于您没有为“/”定义任何路由。所以,(在编辑了 csv 的标题之后)我会做这样的事情:

from flask import *
import pandas as pd
app = Flask(__name__)

@app.route("/tables")
def show_tables():
    data = pd.read_csv("/tmp/a.csv", sep='\s+', quotechar='"')
    data.set_index(['Name'], inplace=True)
    data.index.name=None
    females = data.loc[data.Gender=='F']
    return render_template('view.html',tables=[females.to_html(classes='female')],

    titles = ['na', 'Female surfers'])

@app.route("/")
def show_home():
    return "Hello Guys! Visit: <a href='/tables'> this link </a>"

if __name__ == "__main__":
    app.run(debug=True)