For each row of my data I want positive values together and negative values together:
c1 c2 c3 c4 c5
1 2 3 -1 -2
3 2 -1 2 -9
3 -5 1 2 4
Output
c1 c2 c3 c4 c5 sum_positive sum_negative
1 2 3 -1 -2 6 -3
3 2 -1 2 -9 7 -10
3 -5 1 2 4 10 -5
I was trying to use a for loop like: (G is my df) and add positive and negative elements in 2 list and add them but I thought there might be a better way to do that.
g=[]
for i in range(G.shape[0]):
for j in range(G.shape[1]):
if G.iloc[i,j]>=0:
g.append(G.iloc[i,j])
g.append('skill_next')
Loops or .apply will be pretty slow, so your best bet is to just .clip the values and take the sum directly:
In [58]: df['sum_positive'] = df.clip(lower=0).sum(axis=1)
In [59]: df['sum_negative'] = df.clip(upper=0).sum(axis=1)
In [60]: df
Out[60]:
c1 c2 c3 c4 c5 sum_positive sum_negative
0 1 2 3 -1 -2 6 -3
1 3 2 -1 2 -9 7 -10
2 3 -5 1 2 4 10 -5
Or you can use where:
df['sum_negative'] = df.where(df<0).sum(1)
df['sum_positive'] = df.where(df>0).sum(1)
RESULT:
c1 c2 c3 c4 c5 sum_negative sum_positive
0 1 2 3 -1 -2 -3.0 6.0
1 3 2 -1 2 -9 -10.0 7.0
2 3 -5 1 2 4 -5.0 10.0
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