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

如何在pandas透视表(pivot table)中插入拼接列作为聚合值

解决方法

你只需要对生成的透视表调整列索引的层级顺序,再重新排序即可实现需求,无需提前拼接列。

完整代码

import pandas as pd
import numpy as np
   
# 创建DataFrame
df = pd.DataFrame({'Student': ['John', 'Boby', 'Mina', 'Peter', 'Nicky'],
       'Grade': ['Masters', 'Graduate', 'Graduate', 'Masters', 'Graduate'],
       'Major': ['Liberal Arts', 'Business', 'Sciences', 'Education', 'Law'],
       'Age': [27, 23, 21, 23, 24],
       'City': ['Boston', 'Brooklyn', 'Camden', 'Chicago', 'Manhattan'],
       'State': ['MA', 'NY', 'NJ', 'IL', 'NY'],
       'Years' : [2, 4, 3, 3, 4] })

# 生成透视表
table = pd.pivot_table(df, values =['Age','Years'], index =['Student','City','State'], columns =['Grade', 'Major'], aggfunc = np.sum)

# 调整列层级顺序:将原来在最上层的values维度放到最下层,再按列索引排序
table = table.reorder_levels([1,2,0], axis=1).sort_index(axis=1)

输出效果

Grade                   Graduate                          Masters                         
Major                   Business        Law        Sciences Education        Liberal Arts     
                             Age Years  Age Years      Age Years       Age Years          Age Years
Student City      State                                                                          
Boby    Brooklyn  NY        23.0   4.0  NaN   NaN      NaN   NaN       NaN   NaN          NaN   NaN
John    Boston    MA         NaN   NaN  NaN   NaN      NaN   NaN       NaN   NaN         27.0   2.0
Mina    Camden    NJ         NaN   NaN  NaN   NaN     21.0   3.0       NaN   NaN          NaN   NaN
Nicky   Manhattan NY         NaN   NaN 24.0   4.0      NaN   NaN       NaN   NaN          NaN   NaN
Peter   Chicago   IL         NaN   NaN  NaN   NaN      NaN   NaN      23.0   3.0          NaN   NaN

原理解释

你之前的代码生成的透视表默认将values参数指定的字段放在列索引的最上层,所以会先展示所有Age的分组结果,再展示所有Years的分组结果。通过reorder_levels将Grade、Major放在列索引的前两层,values放在最下层后,每个(年级,专业)组合下都会相邻展示对应的Age和Years数值,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:54:03