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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With