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

Python中Pivot Table如何添加百分比与层级小计?

为Pivot Table添加层级小计并展示百分比

实现步骤

我们可以通过手动计算各层级小计并与原透视表合并,再计算百分比的方式实现,步骤清晰且易于自定义:

1. 导入模块与准备数据

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':['x','y','z','x','y','z'],
                   'B':['one','one','one','two','two','two'],
                   'C':[2,18,2,8,2,18]})

2. 生成基础透视表

# 生成以A、B为索引,求和C的透视表
table = pd.pivot_table(df, index=['A', 'B'], aggfunc=np.sum)

3. 计算各层级小计

计算A层级的小计

# 按A分组求和,得到每个A的小计
subtotals_A = df.groupby('A')['C'].sum().reset_index(name='C')
# 为小计行设置B列标识为"Subtotal",并匹配透视表的多级索引
subtotals_A['B'] = 'Subtotal'
subtotals_A.set_index(['A', 'B'], inplace=True)

计算总计行

grand_total = pd.DataFrame(
    {'C': [df['C'].sum()]},
    index=pd.MultiIndex.from_tuples([('Grand Total', '')], names=['A', 'B'])
)

4. 合并透视表与小计

将基础透视表、A层级小计、总计行合并,并调整排序确保小计在对应层级的明细之后:

# 合并所有数据
combined = pd.concat([table, subtotals_A, grand_total])

# 添加排序键,让明细行在前,小计行在后
combined['sort_key'] = combined.index.get_level_values('B').apply(lambda x: 0 if x not in ['Subtotal', ''] else 1)
# 按A、排序键、B排序,然后删除排序键
combined = combined.sort_values(['A', 'sort_key', 'B']).drop('sort_key', axis=1)

5. 计算百分比列

相对于总计的百分比

grand_total_value = combined.loc[('Grand Total', ''), 'C']
combined['% of Grand Total'] = round((combined['C'] / grand_total_value) * 100, 2)

相对于A层级小计的百分比

# 获取每个A的小计值
subtotal_map = combined.xs('Subtotal', level='B')['C'].to_dict()

# 计算明细行相对于对应A小计的百分比
combined['% of A Subtotal'] = np.where(
    combined.index.get_level_values('B') == 'Subtotal',
    100.0,  # 小计行自身占比为100%
    combined.index.get_level_values('A').map(subtotal_map)
)
combined['% of A Subtotal'] = round((combined['C'] / combined['% of A Subtotal']) * 100, 2)

# 总计行的A层级占比设为100%
combined.loc[('Grand Total', ''), '% of A Subtotal'] = 100.0

最终结果

运行上述代码后,combined dataframe将包含:

  • 原透视表的明细行
  • 每个A分组的小计行
  • 总计行
  • 两列百分比(相对于总计、相对于A层级小计)

示例输出:

C  % of Grand Total  % of A Subtotal
A         B                                           
x         one     2              4.00             20.00
          two     8             16.00             80.00
          Subtotal 10             20.00            100.00
y         one    18             36.00             90.00
          two     2              4.00             10.00
          Subtotal 20             40.00            100.00
z         one     2              4.00             10.00
          two    18             36.00             90.00
          Subtotal 20             40.00            100.00
Grand Total       50            100.00            100.00

优势说明

这种方法无需依赖第三方库或复杂的API调用,完全通过pandas基础操作实现:

  • 自定义程度高:可灵活添加任意层级的小计(如B层级小计)
  • 逻辑清晰:每一步操作目的明确,便于调试和修改
  • 兼容性好:适用于各种版本的pandas,不会因API变更失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 05:15:39