Menu Close

How to sum DataFrame rows for given columns with Python Pandas?

To sum DataFrame rows for given columns with Python Pandas, we can use the sum method.

For instance, we write

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)

to call df.sum with axis set to 1 to sum the row values.

It’ll also ignore non numeric columns when doing the sum.

Posted in Python, Python Answers