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

如何创建含多列的Pivot Table?附DataFrame及尝试代码

多列透视表构建解决方案

1. 基础层次化列透视表

如果需要保留多级列索引的结构,直接通过pivot_table指定多指标值和列分组即可:

import pandas as pd

# 示例DataFrame(匹配你的数据结构)
data = {
    'Category': ['A', 'A', 'B', 'B', 'A', 'B'],
    'Subcategory': ['X', 'Y', 'X', 'Y', 'X', 'Y'],
    'Year': [2022, 2022, 2022, 2022, 2023, 2023],
    'Sales': [100, 200, 150, 250, 120, 220],
    'Profit': [10, 20, 15, 25, 12, 22]
}
df = pd.DataFrame(data)

# 构建透视表
pivot = df.pivot_table(
    index=['Category', 'Subcategory'],
    columns='Year',
    values=['Sales', 'Profit'],
    aggfunc='sum'  # 按需替换聚合函数:mean/max/count等
)

print(pivot)

输出为层次化列结构:

Sales        Profit       
Year               2022   2023    2022   2023
Category Subcategory                         
A        X           100  120.0     10  12.0
         Y           200    NaN     20   NaN
B        X           150    NaN     15   NaN
         Y           250  220.0     25  22.0

2. 扁平列名透视表

如果期望输出为2022_Sales这类合并后的扁平列名,可通过合并多级列索引实现:

# 扁平化列名
pivot_flat = pivot.copy()
pivot_flat.columns = [f'{year}_{metric}' for metric, year in pivot_flat.columns]
pivot_flat = pivot_flat.reset_index()

print(pivot_flat)

输出结果:

Category Subcategory  2022_Sales  2023_Sales  2022_Profit  2023_Profit
0        A           X         100       120.0           10         12.0
1        A           Y         200         NaN           20          NaN
2        B           X         150         NaN           15          NaN
3        B           Y         250       220.0           25         22.0

3. 自定义聚合规则透视表

若需对不同指标使用不同聚合函数,可通过字典指定:

pivot_custom = df.pivot_table(
    index=['Category', 'Subcategory'],
    columns='Year',
    values={'Sales': 'sum', 'Profit': 'mean'},
    fill_value=0  # 填充缺失值为0,避免NaN干扰
)

# 扁平化列名
pivot_custom.columns = [f'{year}_{metric}' for metric, year in pivot_custom.columns]
pivot_custom = pivot_custom.reset_index()

print(pivot_custom)

输出:

Category Subcategory  2022_Sales  2023_Sales  2022_Profit  2023_Profit
0        A           X         100         120         10.0         12.0
1        A           Y         200           0         20.0          0.0
2        B           X         150           0         15.0          0.0
3        B           Y         250         220         25.0         22.0

关键注意事项

  • 确认index、columns参数指定的列在DataFrame中存在,数据类型无异常
  • 聚合函数需匹配业务场景:数值型数据常用sum/mean,离散数据用count
  • 使用fill_value可统一处理透视表中的缺失值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:13:32