Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add positive elements (and negative) in each row?

Tags:

pandas

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') 

2 Answers

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
like image 103
Randy Avatar answered Nov 28 '25 23:11

Randy


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
like image 44
Nk03 Avatar answered Nov 28 '25 23:11

Nk03