Pandas自定义数据重塑并导出为Excel的实现方法
解决方案:按年份分组展示并导出至Excel
针对你的需求,核心是对year分层索引进行分组分块输出,而非单纯的DataFrame重塑。以下是终端文本输出和Excel导出的最优实现:
1. 终端/文本格式输出
通过groupby按年份分组,遍历每个组并打印年份标题与对应数据:
import pandas as pd # 数据预处理代码 world = pd.read_csv("../data/worldstats.csv") cond = world["country"].isin(["Brazil","Canada","Denmark"]) world = world[cond] world = world.set_index(["year","country"]).sort_index() # 按年份分组输出目标格式 for year, group in world.groupby(level="year"): print(f"year {year}") # 移除year索引,仅保留country作为行索引 print(group.reset_index(level="year", drop=True)) print()
2. Excel导出最优方案
使用pandas.ExcelWriter配合openpyxl引擎,实现带格式的分块导出(需先安装openpyxl:pip install openpyxl):
import pandas as pd from openpyxl.styles import Font # 数据预处理(同前) world = pd.read_csv("../data/worldstats.csv") cond = world["country"].isin(["Brazil","Canada","Denmark"]) world = world[cond] world = world.set_index(["year","country"]).sort_index() # 导出到Excel并设置格式 with pd.ExcelWriter("world_data.xlsx", engine="openpyxl") as writer: current_row = 1 bold_font = Font(bold=True) worksheet = writer.book.create_sheet("Data") # 创建工作表 for year, group in world.groupby(level="year"): # 写入年份标题(加粗) worksheet.cell(row=current_row, column=1, value=f"year {year}").font = bold_font current_row += 1 # 写入该年份的数据(自动生成表头) group_reset = group.reset_index(level="year", drop=True) group_reset.to_excel(writer, sheet_name="Data", startrow=current_row, startcol=0) # 更新行号,预留空行分隔不同年份 current_row += len(group_reset) + 2 # +2:表头行+空行
方案说明
- 你尝试的
stack()/pivot()等函数用于重塑数据结构,但你的需求是分块展示/导出,因此groupby是更直接的核心逻辑。 - Excel导出方案通过批量写入分组数据+自定义标题格式,兼顾效率与格式要求,比手动循环单个单元格更高效。
内容的提问来源于stack exchange,提问作者Demeter P. Chen
相关产品推荐
相关产品推荐

