英文:
Error during template rendering | Could not parse the remainder: '(pandas.NaT)' from 'pandas.isnull(pandas.NaT)'
问题
I can help with the translation. Here's the translated content:
我正在尝试在Django应用程序中通过HTML显示一个字典,其中字典的每个值都是一个数据框。
我能够打印出键,但无法打印出数据框,对此我尝试了许多不同的方法。
要么我打印出键值对,但这对人类来说不太可读,要么我会收到“无法解析剩余部分”的错误消息。
以下是views.py的代码片段:
context = {'rail': rail}
return render(request, 'sample_output.html', context)
其中rail是我的字典。
以下是HTML的代码片段:
<table>
<thead>
<tr>
{% for key in rail.keys %}
<th>{{ key }}</th>
{% endfor %}
</tr>
</thead>
<tbody style="height: 400px; overflow-y: scroll;">
{% for key, value in rail.items %}
<tr>
<td>{{ key }}</td>
<td>
<ul>
{% for index, row in value.iterrows %}
<tr>
{% for cell in row %}
<td>
{% if cell is not pandas.isnull(pandas.NaT) %}
{{ cell }}
{% else %}
NaT
{% endif %}
</td>
{% endfor %}
</tr>
{% endfor %}
</ul>
</td>
</tr>
{% endfor %}
</tbody>
</table>
英文:
I'm trying to display a dictionary via html in django app and that each value of dictionary is a dataframe.
I'm able to print key but not dataframe for which I've tried many different approaches.
Either I get key value pair printed which is not very human readable or I get Could not parse the remainder
error
Here's snippet of views.py
context = {'rail': rail}
return render(request, 'sample_output.html', context)
where rail is my dictionary
Here's snippet of html
<table>
<thead>
<tr>
{% for key in rail.keys %}
<th>{{ key }}</th>
{% endfor %}
</tr>
</thead>
<tbody style="height: 400px; overflow-y: scroll;">
{% for key, value in rail.items %}
<tr>
<td>{{ key }}</td>
<td>
<ul>
{% for index, row in value.iterrows %}
<tr>
{% for cell in row %}
<td>
{% if cell is not pandas.isnull(pandas.NaT) %}
{{ cell }}
{% else %}
NaT
{% endif %}
</td>
{% endfor %}
</tr>
{% endfor %}
</ul>
</td>
</tr>
{% endfor %}
</tbody>
</table>
答案1
得分: 1
Use to_html()
with safe
filter:
context = {'rail': {k: v.to_html() for k, v in rail.items()}}
For each dataframe, in your template use <td>{{ value|safe }}</td>
Example:
df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
print(df.to_html())
# Output
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>col1</th>
<th>col2</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1</td>
<td>3</td>
</tr>
<tr>
<th>1</th>
<td>2</td>
<td>4</td>
</tr>
</tbody>
</table>
英文:
Use to_html()
with safe
filter:
context = {'rail': {k: v.to_html() for k, v in rail.items()}}
For each dataframe, in your template use <td>{{ value|safe }}</td>
Example:
df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
print(df.to_html())
# Output
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>col1</th>
<th>col2</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1</td>
<td>3</td>
</tr>
<tr>
<th>1</th>
<td>2</td>
<td>4</td>
</tr>
</tbody>
</table>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论