Given a dataframe as follows:
x1 x2 x3 x4 x5 x6
1 2 3 4 5 6
3 4 5 6 3 3
1 2 3 6 1 2
How could i create a new columns of 'sum' that just adds x1 + x3 + x4
x1 x2 x3 x4 x5 x6
1 2 3 4 5 6
3 4 5 6 3 3
1 2 3 6 1 2
In my actual dataframe i have about 100 columns, so is there a way to do this without having to manually write x1 + x3 + ... + xn
e.g. given a list [x1, x3, x4.. xn] df['sum'] = sum(df[list]) ? Any help appreciated, thanks.
You can use subset of df
and sum
:
print df
x1 x2 x3 x4 x5 x6
0 1 2 3 4 5 6
1 3 4 5 6 3 3
2 1 2 3 6 1 2
print df[['x1', 'x3', 'x4']]
x1 x3 x4
0 1 3 4
1 3 5 6
2 1 3 6
li = ['x1', 'x3', 'x4']
print df[li]
x1 x3 x4
0 1 3 4
1 3 5 6
2 1 3 6
print df[li].sum()
x1 5
x3 11
x4 16
dtype: int64
print df[li].sum(axis=1)
0 8
1 14
2 10
dtype: int64
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