python - 使用 Django 模板标签 'slice' 切片 pandas 数据框?

标签 python django pandas django-templates

我有一个 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/

相关文章:

python - TensorFlow 无法识别 feed_dict 输入

python - 在csv文件python中打印输出

在 heroku 上使用 nested_inline 时 collectstatic 期间出现 Django 错误

python - 如何通过跳过 NaN 从数组/数据帧中获取第一个和最后一个数字对

python - 如何找到所有()一个 Pandas 数据框的正则表达式序列?

python - 如果任何行包含特定字符串,则选择列

python - 向 Django 中长时间运行的方法发送信号

django - 如何使用 heroku 修复 "No module named storages.backends.s3boto"错误?

python - 从多列中查找最接近的值并添加到 Python 中的新列

python - Pandas 在不同数量的行中为每个 ID 选择三行