【问题标题】:How to exporting dataframe to excel sheet with grouping based in categories如何使用基于类别的分组将数据框导出到 Excel 工作表
【发布时间】:2021-04-10 17:02:36
【问题描述】:

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

Col1 Col2 Col3
a 1 2
a 5 6
a 3 0
b 3 12
b 4 21
c 7 31

在 Col1 列中,我有不同大小的目录,每次更新数据库时,行数也会发生变化。

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

【问题讨论】:

    标签: python pandas dataframe grouping xlsxwriter


    【解决方案1】:

    一切皆有可能。这是实现您想要的一种方法。

    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()
    

    文件保存如下:

    如果您展开行,您将获得:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多