【问题标题】:Output a pandas DataFrame in Django with dynamic shape在 Django 中输出具有动态形状的 pandas DataFrame
【发布时间】:2020-08-12 13:45:22
【问题描述】:

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

表格以正确的行数呈现,但表格中的任何内容都无法正确呈现。

【问题讨论】:

    标签: python python-3.x django django-templates


    【解决方案1】:

    我在模板中缺少.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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-08
      • 2023-03-20
      • 2017-12-12
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多