Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: sum DataFrame rows for given columns

I have the following DataFrame:

In [1]:
df = pd.DataFrame({'a': [1, 2, 3],
                   'b': [2, 3, 4],
                   'c': ['dd', 'ee', 'ff'],
                   'd': [5, 9, 1]})

df
Out [1]:
   a  b   c  d
0  1  2  dd  5
1  2  3  ee  9
2  3  4  ff  1

I would like to add a column 'e' which is the sum of columns 'a', 'b' and 'd'.

Going across forums, I thought something like this would work:

df['e'] = df[['a', 'b', 'd']].map(sum)

But it didn't.

I would like to know the appropriate operation with the list of columns ['a', 'b', 'd'] and df as inputs.

like image 505
Colonel Beauvel Avatar asked Oct 04 '22 13:10

Colonel Beauvel


People also ask

How do you sum rows by specific columns in a Pandas DataFrame in Python?

Use DataFrame. sum() to get sum/total of a DataFrame for both rows and columns, to get the total sum of columns use axis=1 param. By default, this method takes axis=0 which means summing of rows.

How do I sum rows in pandas DataFrame?

To sum all the rows of a DataFrame, use the sum() function and set the axis value as 1. The value axis 1 will add the row values.

How do you sum two rows in Python?

Get the sum of all rows in a Pandas Dataframe We called the sum() function on the dataframe without any parameter. So, by default it considered the axis as 0 and added all the rows column wise i.e. added all the values in each column and returned a Series object containing those values.


1 Answers

You can just sum and set param axis=1 to sum the rows, this will ignore none numeric columns:

In [91]:

df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:

In [98]:

col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:

df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
   a  b   c  d  e
0  1  2  dd  5  3
1  2  3  ee  9  5
2  3  4  ff  1  7
like image 345
EdChum Avatar answered Oct 07 '22 01:10

EdChum