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

如何将单级表头的DataFrame数据集转换为三级表头?

单级表头数据集转三级表头实现方案

问题背景

现有名为df的单级表头数据集:

year       cpi       ppi Country code Country name
0  1995  0.107797  0.085297          AUS    Australia
1  1996  0.110997  0.082973          AUS    Australia
2  1997  0.110098  0.083651          AUS    Australia
3  1998  0.107635  0.086049          AUS    Australia
4  1999  0.104969  0.089700          AUS    Australia
5  1995  0.120071  0.129769          MEX       Mexico
6  1996  0.119249  0.142606          MEX       Mexico
7  1997  0.124866  0.151372          MEX       Mexico
8  1998  0.127448  0.153303          MEX       Mexico
9  1999  0.134342  0.159876          MEX       Mexico

需要转换为三级表头的数据集,预期输出:

Country name Australia   Australia    Mexico    Mexico
     Country code       AUS         AUS       MEX       MEX
   Indicator Name       cpi         ppi       cpi       ppi
0            1995  0.107797    0.085297  0.120071  0.129769
1            1996  0.110997    0.082973  0.119249  0.142606
2            1997  0.110098    0.083651  0.124866  0.151372
3            1998  0.107635    0.086049  0.127448  0.153303
4            1999  0.104969      0.0897  0.134342  0.159876

实现代码

通过Pandas的索引操作和层级调整即可完成转换,具体代码如下:

# 1. 设置行索引,将year作为行标识,Country相关字段和指标列区分开
df_indexed = df.set_index(['year', 'Country name', 'Country code'])

# 2. 展开Country相关索引为列层级
df_unstacked = df_indexed.unstack(['Country name', 'Country code'])

# 3. 调整列层级顺序,匹配预期的三级表头结构
df_unstacked.columns = df_unstacked.columns.swaplevel(0, 2).swaplevel(1, 2)

# 4. 给列层级命名
df_unstacked.columns.names = ['Country name', 'Country code', 'Indicator Name']

# 5. 将year从行索引转回普通列
result = df_unstacked.reset_index()

# 输出结果
print(result)

代码说明

  • set_index:把year设为行索引,同时将Country name和Country code纳入多层索引,为后续列展开做准备。
  • unstack:将索引中的Country name和Country code展开为列的层级,此时列层级顺序为[指标(cpi/ppi), Country name, Country code]。
  • swaplevel:两次交换层级位置,将Country name和Country code调整到列的最上层,指标列放在最下层。
  • columns.names:为三个列层级设置名称,完全匹配预期的表头样式。
  • reset_index:把year从行索引转回普通列,和预期输出的行结构一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:40:28