亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Jinja2 使用 GroupBy 并將 Pandas Dataframe 渲染為單獨的

使用 Jinja2 使用 GroupBy 并將 Pandas Dataframe 渲染為單獨的

紫衣仙女 2023-07-11 16:35:48
我的目標是獲取 Pandas 數據框,按列對其進行分組,并將列中的每個組呈現為新的 HTML 文件,最終將其轉換為 PDF 文件。使用鏈接問題中的示例數據:? ? ?Clothing? Color? ?Size0? ? Shirt? ? ?Blue? ? M1? ? Shirt? ? ?Blue? ? L2? ? Shirt? ? ?Black? ?L3? ? Pants? ? ?Black? ?L4? ? Pants? ? ?Blue? ? XL5? ? Jacket? ? Blue? ? L6? ? Jacket? ? Brown? ?L如果我不想為 中的每一項創建一個包含單獨表格的 html 文件Clothing,而是想創建多個 html 文件&mdash;&mdash;每個文件包含一個用于一種顏色的表格:我該怎么做?此代碼根據我選擇的組(在本例中為 的唯一值)成功地將我的數據框呈現Color為具有多個表的單個 HTML 文件。我需要擴展代碼,這意味著無需df['Color']提前對 的唯一值進行硬編碼。import pandas as pdfrom jinja2 import Environmentdf = 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()))謝謝!
查看完整描述

1 回答

?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

您可以使用 . 在循環內創建文件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())


查看完整回答
反對 回復 2023-07-11
  • 1 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號