Sum of only certain columns in a pandas Dataframe

Viewed 2734

I have a dataframe similar to the one below. I need to add up the sum of only certain columns: Jan-16, Feb-16, Mar-16, Apr-16 and May-16. I have these columns in a list called months_list

--------------------------------------------------------------------------------------
| Id               |  Name             | Jan-16 | Feb-16 | Mar-16 | Apr-16 | May-16   |
| 4674393          |  John Miller      |  0     | 1      | 1      | 1      | 1        |
| 4674395          |  Joe Smith        |  0     | 0      | 1      | 1      | 1        |
---------------------------------------------------------------------------------------

My output should look like the below:

--------------------------------------------------------------------------------------
| Id               |  Name             | Jan-16 | Feb-16 | Mar-16 | Apr-16 | May-16   |
| 4674393          |  John Miller      |  0     | 1      | 1      | 1      | 1        |
| 4674395          |  Joe Smith        |  0     | 0      | 1      | 1      | 1        |
|Total             |                   |  0     | 1      | 2      | 2      | 2        |
---------------------------------------------------------------------------------------

A new row called 'Total' should be introduced with a column wise sum for all the columns in my months_list: Jan-16, Feb-16, Mar-16, Apr-16 and May-16

I tried the below and it did not work. I got all NaN values

df.loc['Total',:]= df[months_list].sum(axis=1)
1 Answers

You are using the wrong value of axis parameter.

`axis=0`: Sums the column values
`axis=1`: Sums the row values

Assuming your df to be:

In [4]: df
Out[4]: 
        Id         Name  Jan-16  Feb-16  Mar-16  Apr-16  May-16
0  4674393  John Miller       0       1       1       1       1
1  4674395    Joe Smith       0       0       1       1       1

In [10]: months_list =['Jan-16', 'Feb-16', 'Mar-16', 'Apr-16', 'May-16']

You code should be:

In [12]: df.loc['Total'] = df[months_list].sum()

In [13]: df
Out[13]: 
              Id         Name  Jan-16  Feb-16  Mar-16  Apr-16  May-16
0      4674393.0  John Miller     0.0     1.0     1.0     1.0     1.0
1      4674395.0    Joe Smith     0.0     0.0     1.0     1.0     1.0
Total        NaN          NaN     0.0     1.0     2.0     2.0     2.0
Related