jkortner
jkortner

Reputation: 631

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.

Upvotes: 3

Views: 1681

Answers (2)

BENY
BENY

Reputation: 323226

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

Upvotes: 1

jezrael
jezrael

Reputation: 862591

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

Upvotes: 6

Related Questions