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

在Python Pandas中生成含列组合小计的多级表头DataFrame

生成带多级表头及全组合小计的透视DataFrame

需求说明

给定示例DataFrame:

datesubjectanimalcolorsvalue
JanEnglishcatblue1
FebChemistrydoggreen2

要求通过透视方法生成带多级表头的DataFrame,满足:

  • 使用median作为聚合函数
  • 包含各维度(subject/animal/colors)的全类别小计,用all标识
  • 最终生成27列(计算逻辑:(2个唯一subject+1)×(2个唯一animal+1)×(2个唯一colors+1)=3×3×3=27)

实现代码

1. 构造原始数据

import pandas as pd

# 创建示例DataFrame
df = pd.DataFrame({
    'date': ['Jan', 'Feb'],
    'subject': ['English', 'Chemistry'],
    'animal': ['cat', 'dog'],
    'colors': ['blue', 'green'],
    'value': [1, 2]
})

2. 扩展数据以包含所有小计组合

为了生成每个维度的all小计,需要扩展原始数据,补充所有维度组合的行:

# 定义生成指定维度为'all'的辅助函数
def add_all_rows(df, cols_to_all):
    temp = df.copy()
    temp[cols_to_all] = 'all'
    return temp

# 生成各类小计行
all_dim_all = add_all_rows(df, ['subject', 'animal', 'colors'])
subj_all = add_all_rows(df, ['subject'])
anim_all = add_all_rows(df, ['animal'])
color_all = add_all_rows(df, ['colors'])
subj_anim_all = add_all_rows(df, ['subject', 'animal'])
subj_color_all = add_all_rows(df, ['subject', 'colors'])
anim_color_all = add_all_rows(df, ['animal', 'colors'])

# 合并原始数据与所有小计行
expanded_df = pd.concat(
    [df, all_dim_all, subj_all, anim_all, color_all, subj_anim_all, subj_color_all, anim_color_all],
    ignore_index=True
)

3. 生成多级表头透视表

使用pivot_table生成带多级表头的结果,并按指定顺序排列列:

# 获取各维度的完整类别(含'all')
subjects = df['subject'].unique().tolist() + ['all']
animals = df['animal'].unique().tolist() + ['all']
colors = df['colors'].unique().tolist() + ['all']

# 生成透视表
pivot_result = expanded_df.pivot_table(
    index='date',
    columns=['subject', 'animal', 'colors'],
    values='value',
    aggfunc='median'
)

# 按预设的维度组合重新排序列
pivot_result = pivot_result.reindex(columns=pd.MultiIndex.from_product([subjects, animals, colors]))

结果说明

最终的pivot_result包含27列,多级表头层级为subject→animal→colors,其中每个维度的all表示聚合该维度下的所有类别取中位数。例如:

  • ('all', 'all', 'all')列对应每个date下所有value的中位数
  • ('English', 'all', 'blue')列对应date=Jan时,subject=English、colors=blue的所有animal的value中位数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 00:26:19