广州-李明 2025-02-21 10:44 采纳率: 57.1%
浏览 4

pandas 二次分组后,数据格式问题

问题:一个df进行分组一个中等大小的df1, 之后再对df1进行二次分组, 二次分组的每个df保存到ws工作簿的不同sheet中,然后对每个sheet的数字格式进行处理,现在问题是:只有第一个sheet的数字变成百分制了,第二个sheet到组后的sheet都是没有完成数字变成百分制了,请帮我看下问题出在哪里,如何修改。
补充:以下为代码


```python

df=pd.read_excel(path)
FH = 0 
grouped=df.groupby('Cam')  # 根据列'Cam'的值进行分组
for name, group in grouped:  # 对分组内容进行解压,得到组名和小组数据
 
  # 保存原始表和结果表
  path_save = r"C:\Users\dayin\Desktop\K\KSPLIT.xlsx"
  new_path = path_save.split('.')[0] + '_' + name  + '.' + path.split('.')[1]  # 路径工作簿名称随着这name名称而变化
 
  wb = openpyxl.Workbook()  # 创建一个工作簿
 
  grouped_result = group.groupby('Entity')
  for name_1, group_1 in grouped_result:
      group_1=group_1.reset_index(drop=True)  #重置索引不改变原有数据列名
 
      ws= wb.create_sheet(name_1)
 
      for r in dataframe_to_rows(group_1, index=False, header=True):
        ws.append(r)
      # sheet1原始数据应用格式
 
      # 定义样式
      percent_style = NamedStyle(name="percent_style", number_format="0.00%")  # 百分比格式处理
      float_style = NamedStyle(name="decimal_style", number_format="0.00")  # 2位小数格式处理
 
      for row in ws.iter_rows(min_row=2, min_col=2):  # 数据区域,从第二行开始格式处理
          for cell in row:
              if cell.column in [18, 23, 24]:  # 限定百分比格式的列,数字1表示第1列
                  cell.style = percent_style
              # elif cell.column in [100]:  # 限定2位小数的列,数字5表示第5列
              #     cell.style = float_style
 
  # 保存文件
  sheet_names = wb.sheetnames
  del wb[sheet_names[0]]
  wb.save(new_path)  # 保存动作


```

  • 写回答

4条回答 默认 最新

  • 阿里嘎多学长 2025-02-21 10:44
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    pandas 二次分组后,数据格式问题

    你的问题是:使用 pandas 对一个 DataFrame 进行分组,然后对每个分组进行二次分组,并将每个二次分组保存到不同的 Excel sheet 中。最后,你想对每个 sheet 中的数字格式进行处理。

    问题是:只有第一个 sheet 的数字格式正确,其他 sheet 的数字格式不正确。

    解决方案:

    1. 使用 pandas.DataFrame.to_excel 方法将每个二次分组保存到不同的 Excel sheet 中。
    2. 使用 openpyxl 库对 Excel 文件进行操作,修改每个 sheet 中的数字格式。

    以下是一个示例代码:

    import pandas as pd
    import openpyxl
    
    # 对 DataFrame 进行分组
    df1 = df.groupby('column1')
    
    # 对每个分组进行二次分组
    for name, group in df1:
        group.to_excel(f'sheet_{name}.xlsx', index=False)
    
    # 使用 openpyxl 库对 Excel 文件进行操作
    wb = openpyxl.load_workbook('output.xlsx')
    for sheet_name in wb.sheetnames:
        sheet = wb[sheet_name]
        for row in sheet.iter_rows(values_only=True):
            for cell in row:
                if isinstance(cell, (int, float)):
                    cell.number_format = '0.00'  # 设置数字格式为小数点后两位
    
    wb.save('output.xlsx')
    

    这个示例代码将对每个二次分组保存到不同的 Excel sheet 中,然后使用 openpyxl 库对每个 sheet 中的数字格式进行处理。

    评论

报告相同问题?

问题事件

  • 创建了问题 2月21日