Adding all columns to a data framework

I would like to add all the columns in the DataFrame, and I would like this sum to be added as a new column in the DataFrame.

I want all columns to be accessible, without mentioning the first and last columns in my query.

Is it possible?

+4
source share
3 answers

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
+2
source

Decision

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

you can do it like this:

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

All Articles