如何将dataframe导出到基于类别分组的excel工作表

2024-06-26 00:20:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大约60K行的数据帧,其结构类似于下面的一个:

^{tb1}$

在Col1列中,我有大小不同的cartegories,每次更新数据库时,行数也会改变

可以使用已经格式化的行(类似于发生的https://xlsxwriter.readthedocs.io/working_with_outlines.html)以xlsx格式导出数据帧,但是类别会自动检测到吗


Tags: 数据httpsio数据库htmlwithreadthedocsxlsx
1条回答
网友
1楼 · 发布于 2024-06-26 00:20:52

一切皆有可能。这里有一种方法可以实现你想要的

import pandas as pd

# Create a test dataframe
df = pd.DataFrame({'Col1': ['a', 'a', 'a', 'b', 'b', 'c'],
                   'Col2': [1, 5, 3, 3, 4, 7],
                   'Col3': [2, 6, 0, 12, 21, 31]})

writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']

# Define a format for the first category in the group
bold = workbook.add_format({'bold': True})

# Iterate through the dataframe. If row is the first record of the group apply format and the collapsed '+' symbol,
# for the rest records of the group assign them in the same level and hide them
for row in range(0, df.shape[0]):
    if df.iloc[row, 0] != df.iloc[row-1, 0]:
        cell_format = bold
        outline_option = {'collapsed': True}
    else:
        cell_format = None
        outline_option = {'level': 1, 'hidden': True}

    worksheet.set_row(row+1, None, cell_format, outline_option)

writer.save()

文件的保存方式如下:

enter image description here

如果展开这些行,您将得到: enter image description here

如果输出不是您想要的,您可以调整代码以满足您的需要。但我希望你明白了

相关问题 更多 >