You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Pandas DataFrame按Name拆分到同一Excel文件的不同工作表

按Name分组导出DataFrame到Excel多工作表

要实现将DataFrame按Name字段分组后,每个分组数据存入同一个Excel文件的独立工作表,可按以下步骤操作:

1. 导入依赖库

需要用到pandas处理数据,openpyxl作为多工作表写入的引擎(支持xlsx格式):

import pandas as pd

2. 构建示例DataFrame

data = {
    'Name': ['Employee1','Employee1','Employee1','Employee2','Employee2','Employee2','Employee3','Employee3','Employee3'],
    'Date (July)': [22,23,24,22,23,24,22,23,24],
    'Working_Hours': [7,7,8,8,8,8,8,7,9],
    'Overtime': [0,0,1,1,1,1,1,0,2]
}
dataframe = pd.DataFrame(data)

3. 分组并导出到Excel

通过groupby按Name分组,遍历每个分组将数据写入对应工作表:

# 创建ExcelWriter对象,指定输出文件路径和引擎
with pd.ExcelWriter('employee_hours.xlsx', engine='openpyxl') as writer:
    # 遍历分组:group_name为员工姓名,group_data为对应分组的数据
    for group_name, group_data in dataframe.groupby('Name'):
        # 将分组数据写入以员工姓名命名的工作表,不导出索引列
        group_data.to_excel(writer, sheet_name=group_name, index=False)

关键说明

  • with语句会自动管理文件资源,无需手动关闭ExcelWriter。
  • 直接用Name字段值作为工作表名,确保每个员工的数据对应独立工作表。
  • index=False避免导出不必要的索引列,保持Excel数据整洁。

内容的提问来源于stack exchange,提问作者ioalft

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 00:18:24