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

如何用Pandas生成带分类总计的类Excel多索引透视表

需求描述

现有包含year、type、status、paid、balance、count字段的数据集,当前用下面这段Pandas代码生成透视表:

pivot = (pd.pivot_table(df,
                        index=['status', 'type'],
                        values=['paid', 'balance', 'count'],
                        aggfunc="sum")
           .reset_index()
           .rename_axis(None, axis=1))

这段代码会生成以['status','type']为复合索引、聚合求和的透视表,但现在想要生成类似Excel透视表的格式:每个status分类下先显示该分类的paid、balance、count总计行,再展示对应各type的明细行,示例格式如下:

type      paid    balance   count
 active    1755     3580       40  (running totals for active)
 bank1      500      850        6
 bank2      450      800        8
 bank3      225      940       11
 bank4     580      990        15
...

实现方案

可以通过先分组统计总计,再合并明细数据,最后排序的方式实现需求,具体代码如下:

import pandas as pd

# 1. 生成按status+type聚合的明细数据
detail_df = pd.pivot_table(df,
                          index=['status', 'type'],
                          values=['paid', 'balance', 'count'],
                          aggfunc="sum").reset_index()

# 2. 生成每个status的总计数据
total_df = detail_df.groupby('status')[['paid', 'balance', 'count']].sum().reset_index()
# 给总计行的type列设置为status的值,对应示例里的总计行显示
total_df['type'] = total_df['status']

# 3. 添加排序标记,合并后排序让总计行排在前面
total_df['sort_key'] = 0  # 总计行标记为0,优先排序
detail_df['sort_key'] = 1  # 明细行标记为1

combined_df = pd.concat([total_df, detail_df], ignore_index=True)
# 按status分组,先排总计行,再排明细行
result_df = combined_df.sort_values(by=['status', 'sort_key', 'type'], ignore_index=True)

# 4. 清理辅助列,调整列顺序到需求格式
result_df = result_df.drop(columns=['sort_key', 'status'])[['type', 'paid', 'balance', 'count']]

# 查看最终结果
print(result_df)

关键说明

  • 步骤1:生成原始明细透视表,逻辑和你原来的代码一致
  • 步骤2:对status分组求和得到总计行,把type列设为status的值,对应示例中总计行的type显示
  • 步骤3:用sort_key区分总计和明细行,排序时让同status的总计行排在所有明细行前面
  • 步骤4:删除辅助的sort_key和status列,调整列顺序到需求的格式

如果需要保留status列用于后续筛选或区分,可以跳过删除status列的步骤,自行调整列顺序即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:40:18