Search code examples
pythonpandasdataframepivot-table

how to add row totals to simple df using pivot table


I have a simple 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

Even though pivot_table is meant for more complicated data, I can use it to quickly generate column totals:

>>> 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

Can I easily add row totals using this method?

Desired Output is:

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

Solution

  • You can do this, by transposing, pivoting and transposing again:

    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,sort=False).T
    

    Output:

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

    But why not just use 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)
    

    Output:

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