【问题标题】:Slicing pandas dataframe using Django template tag 'slice'?使用 Django 模板标签“切片”对熊猫数据框进行切片?
【发布时间】:2017-08-30 07:29:30
【问题描述】:

我有一个 pandas 数据框,我将它传递给 Django HTML。我想在使用 Django 的模板过滤器“切片”打印数据框时对数据框进行子集化。 Slice 适用于 list 和 django 的对象 QuerySet 但不知何故它在与 pandas 数据框一起使用时不起作用。我想知道为什么以及如何可以或不能工作。

示例:我在下面的示例中切片了 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>

【问题讨论】:

    标签: python django pandas django-templates


    【解决方案1】:

    您想切片迭代器,但可能只需要使用tolist

     {% for row in df.values.tolist|slice:"1" %}
     <tr>
       <td> {{row.0}} </td>
       <td> {{row.1}} </td>
     </tr>
     {% endfor %}
    

    【讨论】:

    • 这完美!另外,感谢您帮助添加 {% endfor %}。
    猜你喜欢
    • 1970-01-01
    • 2017-08-13
    • 2021-02-27
    • 2021-09-01
    • 2015-05-11
    • 2022-11-14
    • 2018-12-24
    • 2015-08-11
    • 1970-01-01
    相关资源
    最近更新 更多