vsoler
vsoler

Reputation: 1173

Adding up all columns in a dataframe

I'd like to add up all the columns in a DataFrame, and I'd like this sum added as a new column in the DataFrame.

I want "all" the columns available, without mentioning the first and last columns in my query.

Is this possible?

Upvotes: 4

Views: 70

Answers (3)

jezrael
jezrael

Reputation: 862591

Use sum:

import pandas as pd
import numpy as np

#random dataframe
np.random.seed(1)
df1 = pd.DataFrame(np.random.randint(10, size=(3,5)))
df1.columns = list('ABCDE')
print df1
   A  B  C  D  E
0  5  8  9  5  0
1  0  1  7  6  9
2  2  4  5  2  4

df1['sum'] = df1.sum(axis=1)
print df1
   A  B  C  D  E  sum
0  5  8  9  5  0   27
1  0  1  7  6  9   23
2  2  4  5  2  4   17

Another solution for creating new columns is assign:

print df1.assign(sum=df1.sum(axis=1))
   A  B  C  D  E  sum
0  5  8  9  5  0   27
1  0  1  7  6  9   23
2  2  4  5  2  4   17

Upvotes: 2

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

you can do it like this:

df['sum'] = df.sum(axis=1)

Upvotes: 1

piRSquared
piRSquared

Reputation: 294248

Solution

pd.concat([df, df.sum(axis=1)], axis=1)

Upvotes: 1

Related Questions