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

如何用pivot_table为简单DataFrame添加行总计?

用pivot_table同时实现行总计与列总计

首先,你的初始DataFrame定义如下:

import pandas as pd
a = pd.DataFrame({'a': [1, 2, 3], 'b': [2, 3, 4], 'c': [3, 4, 5]}, index=["type1","type2","type3"])

输出结果:

a  b  c
type1  1  2  3
type2  2  3  4
type3  3  4  5

你已经知道用pivot_table生成列总计:

a.pivot_table(index=a.index, margins=True, aggfunc=sum)

得到:

a  b  c
type1  1  2  3
type2  2  3  4
type3  3  4  5
All    6  9  12

要同时添加行总计,只需要先给原DataFrame新增一个计算每行总和的All列,再用pivot_table生成包含列总计的结果即可:

# 添加行总计列
a['All'] = a.sum(axis=1)
# 生成包含行、列总计的结果
result = a.pivot_table(index=a.index, margins=True, aggfunc=sum)

运行后得到的结果就是你期望的:

a  b  c  All
type1  1  2  3    6
type2  2  3  4    9
type3  3  4  5   12
All    6  9  12   27

如果你想一步完成,也可以用链式调用:

result = a.assign(All=a.sum(axis=1)).pivot_table(index=a.index, margins=True, aggfunc=sum)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:17:53