Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 在每行中添加正元素(和负元素)?_Pandas - Fatal编程技术网

Pandas 在每行中添加正元素(和负元素)?

Pandas 在每行中添加正元素(和负元素)?,pandas,Pandas,对于我的每一行数据,我希望将正值和负值放在一起: c1 c2 c3 c4 c5 1 2 3 -1 -2 3 2 -1 2 -9 3 -5 1 2 4 输出 c1 c2 c3 c4 c5 sum_positive sum_negative 1 2 3 -1 -2 6 -3 3 2 -1 2 -9 7

对于我的每一行数据,我希望将正值和负值放在一起:

   c1   c2  c3  c4  c5
    1   2   3  -1   -2
    3   2   -1  2   -9
    3   -5   1   2   4
输出

   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
我试图使用一个
for循环
比如:(
G
是我的df),在2个列表中添加积极和消极元素,然后添加它们,但我认为可能有更好的方法

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

循环或
.apply
将非常缓慢,因此您最好的选择是只
。剪裁
值并直接获取总和:

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

或者您可以使用
,其中

df['sum_negative'] = df.where(df<0).sum(1)
df['sum_positive'] = df.where(df>0).sum(1)
   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