我有一个 pandas 数据框,我将其传递到 Django HTML 中。我想在使用 Django 的模板过滤器“切片”打印数据框时对数据框进行子集化。 Slice 适用于列表和 django 的对象 QuerySet,但不知何故与 pandas dataframe 一起使用时它不起作用。我想知道为什么以及如何这可以或不能。
示例:我在下面的示例中切片 1 行,但当我的代码运行时,它显示所有 3 行。
示例代码:
在views.py中:
## Libraries
from django.shortcuts import render
from django.http import HttpResponse
import pandas as pd
def dataframe_view(request):
## Creating pandas dataframe
d = {'alphabet': ['a','b','c'], 'num':[1,2,3]}
df = pd.DataFrame(d)
return render(request, 'dataframe.html', {'df':df})
在 dataframe.html
<html>
<body>
...
<table>
<thead>
<tr>
<th>{{ df.columns.0 }} </td>
<th>{{ df.columns.1 }} </td>
<tr>
</thead>
<tbody>
{% for index, row in df.iterrows|slice:":1" %}
<tr>
<td> {{row.0}} </td>
<td> {{row.1}} </td>
</tr>
{% endfor %}
</tbody>
</table>
...
</body>
</html>
最佳答案
您想要切片迭代器,但可能您只需要使用tolist
{% for row in df.values.tolist|slice:"1" %}
<tr>
<td> {{row.0}} </td>
<td> {{row.1}} </td>
</tr>
{% endfor %}
关于python - 使用 Django 模板标签 'slice' 切片 pandas 数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45954486/