如何显示一个 pandas 数据框作为烧瓶,自助表? [英] How to show a pandas dataframe as a flask-boostrap table?

查看:339
本文介绍了如何显示一个 pandas 数据框作为烧瓶,自助表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



数据(.csv表):

我想用一个瓶子来显示一个熊猫数据框作为boostrap-html表, / p>

 姓名出生月份起源年龄性别
卡莉Jan Uk 10 F
Rachel Sep英国20 F
Nicky Sep MEX 30 F
Wendy Oct英国40 F
Judith Nov MEX 39 F

python代码( python_script.py ):

  from烧瓶导入* 
导入pandas作为pd
app =烧瓶(__ 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','女性冲浪者'])


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


$ b 模板目录( view.html ):

 <!doctype html> 
< title>简单表< / title>
< link rel = stylesheet type = text / css href ={{url_for('static',filename ='style.css')}}>
< div class = page>
< h1>冲浪者组< / h1>
{%用于表格中的表格%}
< h2> {{titles [loop.index]}}< / h2>
{{table | safe}}
{%endfor%}
< / div>

boostrap 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;
颜色:白色;
}

.female th {
background-color:#77dd77;
颜色:白色;
}

tr:nth-​​child(奇数){background-color:#eee; }
tr:nth-​​child(偶数){background-color:#fff; }
$ b tr:hover {background-color:#ffff99;}

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

  * Running在http://127.0.0.1:5000/(按CTRL + C退出)
*用stat
重启*调试器处于活动状态!
* Debugger pin code:123-221-151

我得到了两个问题:a发现错误,当我去 http://127.0.0.1:5000/tables 我得到了一个 builtins.KeyError KeyError:'Name'。任何想法如何显示熊猫数据框作为与熊猫和烧瓶表?

解决方案

这里的问题是与 data.csv 文件。

 在[45]中, :pd.read_csv(/ tmp / a.csv)
Out [45]:
姓名出生月份起源年龄性别
0 Carly Jan Uk 10 F
1 Rachel Sep英国20 F
2 Nicky 9月MEX 30 F
3 Wendy 10月英国40 F
4 Judith 11月MEX 39 F

在[46]:df = pd。 read_csv(/ tmp / a.csv)

在[47]中:df.columns
Out [47]:Index([u'Name Birth Month Origin Age Gender'],正如你所看到的,只有一列而不是四列,而不是四列,因为它不能理解出生月应该是一列。为了解决这个问题,你可以打开文件并把第一行改成:

 NameBirth MonthOrigin 年龄性别



然后在阅读csv时:

 在[62]中:pd.read_csv(/ tmp / a.csv,sep ='\s +',quotechar ='')
出[62]:
姓名出生月份起源年龄性别
0 Carly Jan Uk 10 F
1 Rachel Sep英国20 F
2 Nicky Sep MEX 30 F
3 Wendy Oct英国40 F
4 Judith Nov MEX 39 F

也改变了出生月 Birth_Month



'404 Not Found'错误,问题在于你没有为'/'定义任何路由,所以(在编辑csv头部之后)我会这样做:

  from flask import * 
将pandas导入为pd
app = Flask(__ nam e__)

@ 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 = ['呐','女冲浪者'])

@ app.route(/)
def show_home():
returnHello Guys!请访问:< a href ='/ tables'>这个链接< / a>

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


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

The data (.csv table):

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):

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 templates directory (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:

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:

 * 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/tables I got an builtins.KeyError KeyError: 'Name'. Any idea of how to show a pandas dataframe as a table with pandas and flask?.

解决方案

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

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:

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 Month to Birth_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:

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)

这篇关于如何显示一个 pandas 数据框作为烧瓶,自助表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆