Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum N columns in python?

I've a pandas df and I'd like to sum N of the columns. The df might look like this:

A B C D ... X

1 4 2 6     3
2 3 1 2     2 
3 1 1 2     4
4 2 3 5 ... 1

I'd like to get a df like this:

A Z

1 15
2 8
3 8
4 11

The A variable is not an index, but a variable.

like image 980
jkortner Avatar asked Sep 27 '26 06:09

jkortner


2 Answers

Use join for new Series created by sum all columns without A:

df = df[['A']].join(df.drop('A', 1).sum(axis=1).rename('Z'))

Or extract column A first by pop:

df = df.pop('A').to_frame().join(df.sum(axis=1).rename('Z'))

If want select columns by positions use iloc:

df = df.iloc[:, [0]].join(df.iloc[:, 1:].sum(axis=1).rename('Z'))

print (df)
   A   Z
0  1  15
1  2   8
2  3   8
3  4  11
like image 58
jezrael Avatar answered Sep 28 '26 20:09

jezrael


You can groupby column

df.groupby(['A']+['Z']*(df.shape[1]-1),axis=1).sum()
Out[252]: 
   A   Z
0  1  15
1  2   8
2  3   8
3  4  11
like image 45
BENY Avatar answered Sep 28 '26 20:09

BENY