如何使用数据透视表将行总计添加到简单的 df

问题描述 投票:0回答:1

我有一个简单的 df:

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

我可以使用此方法轻松添加行总计吗?

期望的输出是:

      a  b  c   All
type1  1  2   3   6 
type2  2  3   4   9 
type3  3  4   5  12 
All    6  9  12  27 
pandas dataframe pivot-table
1个回答
0
投票

可以通过转置、旋转、再次转置来做到这一点:

a = pd.DataFrame({'a': [1, 2, 3], 'b': [2, 3, 4], 'c': [3, 4, 5]},index=["type1","type2","type3"])
a = a.pivot_table(index=a.index,margins=True,aggfunc=sum)
a = a.T.pivot_table(index=a.columns,margins=True,aggfunc=sum).T

输出:

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

但为什么不直接使用

sum
:

a = pd.DataFrame({'a': [1, 2, 3], 'b': [2, 3, 4], 'c': [3, 4, 5]},index=["type1","type2","type3"])
a.loc['All'] = a.sum()
a['All'] = a.sum(axis=1)

输出:

       a  b   c  All
type1  1  2   3    6
type2  2  3   4    9
type3  3  4   5   12
All    6  9  12   27
© www.soinside.com 2019 - 2024. All rights reserved.