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

如何调整Pandas透视表层级:将Duration设为第0层级

问题描述

现有如下结构的DataFrame:

客户机构货币交易量收入Duration
PeterXYZ LtdCNY, INR203,00001-Oct-2022
Johnabc LtdINR718401-Oct-2022
Maryaaa LtdUSD34303-Oct-2022
Johnbbb LtdTHB172,30004-Oct-2022
Danyccc LtdCNY, INR , KRW4515,10004-Oct-2022

当前使用如下代码执行透视操作:

df = pd.pivot_table(df, values=['runs', 'volume','revenue'],
                        index=['customer', 'organization', 'currency'],
                        columns=['Duration'],
                        aggfunc=sum,
                        fill_value=0
                  )

当前生成的透视表中,第0层级为volume、revenue等指标,Duration为第1层级。现需求将Duration设为第0层级,volume、revenue、runs作为其子层级,请问该如何实现?

解决方案

可以通过调整列层级顺序或重塑数据后透视两种方式实现目标结构:

方法1:生成透视表后交换层级

先执行原透视表代码,再对列索引交换层级并排序,直接调整层级顺序:

# 生成原透视表
df_pivot = pd.pivot_table(df, values=['runs', 'volume','revenue'],
                          index=['customer', 'organization', 'currency'],
                          columns=['Duration'],
                          aggfunc=sum,
                          fill_value=0
                    )
# 交换列的层级,将Duration设为第0层,指标作为子层级
df_pivot = df_pivot.swaplevel(axis=1).sort_index(axis=1)

方法2:先重塑数据再透视

先将宽表转为长表,把指标列转为单独字段,再重新透视直接得到目标层级结构:

# 宽表转长表,提取指标列作为单独的metric字段
df_melted = df.melt(id_vars=['customer', 'organization', 'currency', 'Duration'],
                    value_vars=['runs', 'volume','revenue'],
                    var_name='metric',
                    value_name='value')
# 重新透视,将Duration设为列的第0层级,metric作为子层级
df_pivot = df_melted.pivot_table(index=['customer', 'organization', 'currency'],
                                 columns=['Duration', 'metric'],
                                 values='value',
                                 aggfunc=sum,
                                 fill_value=0)

两种方法均能实现需求,方法1更直接高效,适合已有透视表的场景;方法2适合从原始数据直接构建目标结构的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:01:31