Pandas 数据框到烧瓶模板作为 json [重复]
Posted
技术标签:
【中文标题】Pandas 数据框到烧瓶模板作为 json [重复]【英文标题】:Pandas dataframe to flask template as a json [duplicate] 【发布时间】:2018-06-11 13:22:10 【问题描述】:我尝试在烧瓶模板中输出熊猫数据框。我的想法是将其转换为 json,然后循环遍历表
我测试了这个
jsonfiles = df.to_json(orient='records')
return render_template('index.html', ctrsuccess=jsonfiles)
在模板中我尝试这样输出:
%if ctrsuccess %
<div class="table-responsive">
<table class="table table-striped">
<tbody>
%for ctrrow in ctrsuccess %
<tr>
<td> ctrrow['positionint'] </td>
</tr>
%endfor%
</tbody>
</table>
</div>
%endif%
在模板中,如果我只是绘制 ctrsuccess,我会得到一个外观正确的 json。但是桌子是空的
["positionint":1.0,"clicks":1138.0,"impressions":4768.0,"ctr":0.2386744966,"clickCtr10p":1251.8,"clickCtr50p":1707.0,"clickCtr100p":2276.0,"positionint":2.0,"clicks":3160.0,"impressions":49899.0,"ctr":0.0633279224,"clickCtr10p":3476.0,"clickCtr50p":4740.0,"clickCtr100p":6320.0,"positionint":3.0,"clicks":1255.0,"impressions":50020.0,"ctr":0.025089964,"clickCtr10p":1380.5,"clickCtr50p":1882.5,"clickCtr100p":2510.0,"positionint":4.0,"clicks":363.0,"impressions":39077.0,"ctr":0.0092893518,"clickCtr10p":399.3,"clickCtr50p":544.5,"clickCtr100p":726.0,"positionint":5.0,"clicks":216.0,"impressions":18419.0,"ctr":0.011727021,"clickCtr10p":237.6,"clickCtr50p":324.0,"clickCtr100p":432.0,"positionint":6.0,"clicks":307.0,"impressions":15447.0,"ctr":0.0198744093,"clickCtr10p":337.7,"clickCtr50p":460.5,"clickCtr100p":614.0,"positionint":7.0,"clicks":248.0,"impressions":24709.0,"ctr":0.0100368287,"clickCtr10p":272.8,"clickCtr50p":372.0,"clickCtr100p":496.0,"positionint":8.0,"clicks":236.0,"impressions":26853.0,"ctr":0.0087885897,"clickCtr10p":259.6,"clickCtr50p":354.0,"clickCtr100p":472.0,"positionint":9.0,"clicks":139.0,"impressions":26577.0,"ctr":0.0052300862,"clickCtr10p":152.9,"clickCtr50p":208.5,"clickCtr100p":278.0,"positionint":10.0,"clicks":23.0,"impressions":2046.0,"ctr":0.0112414467,"clickCtr10p":25.3,"clickCtr50p":34.5,"clickCtr100p":46.0,"positionint":null,"clicks":7085.0,"impressions":257815.0,"ctr":null,"clickCtr10p":7793.5,"clickCtr50p":10627.5,"clickCtr100p":14170.0,"positionint":null,"clicks":null,"impressions":null,"ctr":null,"clickCtr10p":1417.0,"clickCtr50p":7085.0,"clickCtr100p":14170.0]
【问题讨论】:
【参考方案1】:根据 pandas 文档,to_json 呈现一个 json 字符串,您可以通过 type(jsonfiles)
确认。虽然打印输出看起来像一个 json 对象,但单引号会在开头和结尾换行。
要解决,只需导入内置的json
模块(Python 标准库的一部分)并使用loads
方法将to_json
字符串解析为json 对象:
import json
...
jsonfiles = json.loads(df.to_json(orient='records'))
return render_template('index.html', ctrsuccess=jsonfiles)
【讨论】:
以上是关于Pandas 数据框到烧瓶模板作为 json [重复]的主要内容,如果未能解决你的问题,请参考以下文章