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

如何用Pandas高效将指定DataFrame重塑为多层列结构?

如何用Pandas原生方法高效重塑DataFrame结构

原始DataFrame数据:

ts type  value1  value2
0   1  foo      10      16
1   1  bar      11      17
2   2  foo      12      18
3   2  bar      13      19
4   3  foo      14      20
5   3  bar      15      21

需要将其重塑为以下多级列索引结构:

foo           bar
  value1 value2 value1 value2
1     10     16     11     17
2     12     18     13     19
3     14     20     15     21

方法1:使用pivot原生函数

pivot是Pandas专门为行列转换设计的高效工具,直接指定索引、列名和值列即可完成重塑:

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'ts': [1,1,2,2,3,3],
    'type': ['foo','bar','foo','bar','foo','bar'],
    'value1': [10,11,12,13,14,15],
    'value2': [16,17,18,19,20,21]
})

# 执行重塑
result = df.pivot(index='ts', columns='type', values=['value1', 'value2'])
# 调整列层级顺序,使其与目标结构完全匹配
result = result.swaplevel(axis=1).sort_index(axis=1)

执行后输出结果:

foo           bar
  value1 value2 value1 value2
ts                           
1     10     16     11     17
2     12     18     13     19
3     14     20     15     21

方法2:使用set_index + unstack

通过设置多层索引再展开列的方式,同样是Pandas底层优化的高效操作:

result = df.set_index(['ts', 'type']).unstack('type')
# 调整列层级顺序
result = result.swaplevel(axis=1).sort_index(axis=1)

特殊场景处理

如果数据中存在重复的(ts, type)组合,可以用pivot_table指定聚合函数处理:

# 以保留第一个匹配值为例
result = df.pivot_table(index='ts', columns='type', values=['value1', 'value2'], aggfunc='first')
result = result.swaplevel(axis=1).sort_index(axis=1)

以上两种方法均为Pandas原生向量化操作,避免了手动循环的低效问题,处理大规模数据时优势明显。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:05:23