如何解决在Django中以动态形状输出pandas DataFrame
我有一个pandas DataFrame,它具有基于查询的不同列,该查询在后端生成此DataFrame。
要在Django中输出它,一种简单的方法是使用.to_html()
方法,但由于我需要对模板中的表格属性进行多次调整,因此不适用于我的用例。
是否可以动态输出?
我以为我可以将两个副本发送到Template,一个副本使用.to_dict()
方法用于生成标题,另一个副本使用to_dict(orient='records')
用于生成表,但是它没有按预期工作。
df = pd.DataFrame({
'col1': [1,2,3,4],'col2': ['A','B','C','D']
})
context = {
'df_dict': df.to_dict(),'df_rec': df.to_dict(orient='records')
}
在HTML模板中:
<table>
<thead>
<tr>
{% for key,value in df_dict.items %}
<th>{{ key }}</th>
{% endfor %}
</tr>
</thead>
{% for rec in df_rec %}
<tr>
{% for ii in rec %}
<td>{{ rec.ii }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
表呈现的行数正确,但表中的任何内容均无法正确呈现。
解决方法
我在模板中错过了一个.items
通话:
<table>
<thead>
<tr>
{% for key,value in df_dict.items %}
<th>{{ key }}</th>
{% endfor %}
</tr>
</thead>
{% for rec in df_rec %}
<tr>
{% for i2,k2 in rec.items %}
<td>{{ k2 }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。