选择带条件的列数据并将其移动到新列

2024-05-23 20:05:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下所示的数据帧。你知道吗

T$QOOR
   3
  14
  12
  -6
 -19
   9

我想把正数和负数移到新的列中。你知道吗

sls_item['SALES'] = sls_item['T$QOOR'].apply(lambda x: x if x >= 0 else 0)
sls_item['RETURN'] = sls_item['T$QOOR'].apply(lambda x: x*-1 if x < 0 else 0)

结果如下。你知道吗

T$QOOR    SALES    RETURN    
   3        3         0
  14       14         0
  12       12         0
  -6        0        -6
 -19        0       -19
   9        9         0

除了使用apply之外,还有更好更干净的方法吗?你知道吗


Tags: 数据方法lambdareturnifitemelseapply
2条回答

assgin+where

df.assign(po=df.where(df['T$QOOR']>0,0),ne=df.where(df['T$QOOR']<0,0))
Out[1355]: 
   T$QOOR  ne  po
0       3   0   3
1      14   0  14
2      12   0  12
3      -6  -6   0
4     -19 -19   0
5       9   0   9

^{}^{},也^{}用于乘以-1

sls_item['SALES'] = sls_item['T$QOOR'].clip_lower(0)
sls_item['RETURN'] = sls_item['T$QOOR'].clip_upper(0).mul(-1)
print (sls_item)
   T$QOOR  SALES  RETURN
0       3      3       0
1      14     14       0
2      12     12       0
3      -6      0       6
4     -19      0      19
5       9      9       0

使用^{}^{}

sls_item['SALES'] = sls_item['T$QOOR'].where(lambda x: x >= 0, 0)
sls_item['RETURN'] = sls_item['T$QOOR'].where(lambda x: x < 0, 0) * -1
print (sls_item)
   T$QOOR  SALES  RETURN
0       3      3       0
1      14     14       0
2      12     12       0
3      -6      0       6
4     -19      0      19
5       9      9       0

mask = sls_item['T$QOOR'] >=0
sls_item['SALES'] = np.where(mask, sls_item['T$QOOR'], 0)
sls_item['RETURN'] = np.where(~mask, sls_item['T$QOOR'] * -1, 0)
print (sls_item)
   T$QOOR  SALES  RETURN
0       3      3       0
1      14     14       0
2      12     12       0
3      -6      0       6
4     -19      0      19
5       9      9       0

相关问题 更多 >