Sum multilevel columns in a pandas MultiIndex DataFrame

Issue

Question:- get the total of all one two columns?

first        bar                 baz                 foo   
second       one       two       one       two       one    two  
A       0.895717  0.805244  1.206412  2.565646  1.431256   1.431256 
B       0.410835  0.813850  0.132003  0.827317  0.076467   0.076467     
C       1.413681  1.607920  1.024180  0.569605  0.875906   0.875906 

output:-

first        bar                 baz                 foo   
          one       two       one       two        one      two 
A       0.895717  0.805244  1.206412  2.565646   1.431256  1.431256
B       0.410835  0.813850  0.132003  0.827317   0.076467  0.076467      
C       1.413681  1.607920  1.024180  0.569605   0.875906  0.875906 
Total    sum        sum      sum       sum         sum      sum 

Solution

If need same value per first level of MultiIndex use:

df.loc['Total'] = df.sum().groupby(level=0).transform('sum')
print (df)
            bar                 baz                 foo          
            one       two       one       two       one       two
A      0.895717  0.805244  1.206412  2.565646  1.431256  1.431256
B      0.410835  0.813850  0.132003  0.827317  0.076467  0.076467
C      1.413681  1.607920  1.024180  0.569605  0.875906  0.875906
Total  5.947247  5.947247  6.325163  6.325163  4.767258  4.767258

Or if need sum each column separately:

df.loc['Total'] = df.sum()
print (df)
            bar                 baz                 foo          
            one       two       one       two       one       two
A      0.895717  0.805244  1.206412  2.565646  1.431256  1.431256
B      0.410835  0.813850  0.132003  0.827317  0.076467  0.076467
C      1.413681  1.607920  1.024180  0.569605  0.875906  0.875906
Total  2.720233  3.227014  2.362595  3.962568  2.383629  2.383629

Answered By – jezrael

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published