pythonpandassumrowsum

total of all rows in new column pandas


question:- get the total of all one two columns

              bar                 baz                 foo              
          one       two       one       two       one    two        
name
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:-

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

Solution

  • You can aggregate per secon dlevel of MultiIndex in columns and then add first level all for MultiIndex, so possible use left join by DataFrame.join:

    df1 = pd.concat({'all': df.groupby(level=1, axis=1).sum().add_prefix('total_')}, axis=1)
    df = df.join(df1)
    print (df)
            bar                 baz                 foo                 all  \
            one       two       one       two       one       two total_one   
    A  0.895717  0.805244  1.206412  2.565646  1.431256  1.431256  3.533385   
    B  0.410835  0.813850  0.132003  0.827317  0.076467  0.076467  0.619305   
    C  1.413681  1.607920  1.024180  0.569605  0.875906  0.875906  3.313767   
    
                 
      total_two  
    A  4.802146  
    B  1.717634  
    C  3.053431