如何在有条件的情况下减去熊猫中的两列

时间:2020-05-07 06:33:55

标签: pandas

我的df以下

Country    Val1 Val2
Australia  4      7
Bambua     23     44
Tambua     24     2

如何减去两列

  • df ['Val1']-如果Val1大于'Val2',则为df ['Val2']

  • df ['Val2']-如果Val2大于'Val1',则为df ['Val1']

2 个答案:

答案 0 :(得分:3)

您也可以只计算绝对值:

pdf['diff'] = np.abs(pdf.Val1 - pdf.Val2)
     Country  Val1  Val2  diff
0  Australia     4     7     3
1     Bambua    23    44    21
2     Tambua    24     2    22

答案 1 :(得分:0)

使用numpy.where

df['new'] = np.where(df['Val1'] > df['Val2'], 
                     df['Val1'] - df['Val2'], 
                     df['Val2'] - df['Val1'])

print (df)
     Country  Val1  Val2  new
0  Australia     4     7    3
1     Bambua    23    44   21
2     Tambua    24     2   22