使用 GroupBy 和渲染 Pandas Dataframe 作为单独的 HTML 文件使用 Jinja2

Use GroupBy and Render Pandas Dataframe as Separate HTML files using Jinja2

在以下人员的帮助下:

最终,我的目标是获取一个 Pandas 数据框,按列对其进行分组,并将列中的每个组渲染为一个新的 HTML 文件,目的是将其转换为一个 PDF 文件,最终。

使用链接问题中的示例数据:

     Clothing  Color   Size
0    Shirt     Blue    M
1    Shirt     Blue    L
2    Shirt     Black   L
3    Pants     Black   L
4    Pants     Blue    XL
5    Jacket    Blue    L
6    Jacket    Brown   L

如果我想创建多个 html 文件,而不是一个 html 文件,其中每个项目都有单独的 tables Clothing,每个文件包含一个table 一种颜色:我该怎么做?

此代码根据我选择的组成功呈现了我的数据框,在本例中为 Color 的唯一值,作为具有多个 table 的单个 HTML 文件。

我需要代码进行扩展,这意味着不需要提前对 df['Color'] 的唯一值进行硬编码。

import pandas as pd
from jinja2 import Environment

df = pd.DataFrame([('Shirt','Blue','M'), ('Shirt','Blue','L'), ('Shirt','Black','L'), ('Pants','Black','L'), ('Pants','Blue','XL'), ('Jacket','Blue','L'), ('Jacket','Brown','L')], columns=['Clothing', 'Color', 'Size'])

env = Environment()
tmpl = env.from_string( '''
{% for df_split in df_splits %}
<div>
{{df.loc[df['Color'] == df_split].to_html()}}
</div>
{% endfor %}''')

print(tmpl.render(df=df,df_splits = df['Color'].unique()))

谢谢!

您可以使用 groupby() 在循环内创建文件。这是一个例子:

tmpl = env.from_string("""
    <div>
    {{ df.to_html(index=False) }}
    </div>
""")

for color_name, group_df in df.groupby(['Color']):
    content = tmpl.render(df=group_df)
    file_path = '/tmp/{f_name}.html'.format(f_name=color_name)
    with open(file_path, 'w+') as file:
        print('writing to file {f}'.format(f=file_path))
        # print(content)  # check content before write if you need
        file.write(content)

    # check content after write if you need
    # with open(file_path) as file:
    #     print('reading file {f}. content:'.format(f=file_path))
    #     print(file.read())