Home > Mobile >  Sum multilevel columns in a pandas MultiIndex DataFrame
Sum multilevel columns in a pandas MultiIndex DataFrame

Time:06-10

enter code here

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 

CodePudding user response:

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