使用pandas将值从一列替换为另一列?

时间:2017-12-23 10:38:39

标签: python pandas dataframe

我有一个数据框:

       subtracted      Subs        hrs  
0      281871.120   450878.77      0.00    
1      221343.432   229535.34      0.00     
2      197454.408    32080.93      0.00    
3      41934.000    -9853.07     32080.93

我想将正数值(相对于子列)从减去列替换为hrs列。

预期产出:

       subtracted      Subs        hrs  
0      281871.120   450878.77      281871.120   
1      221343.432   229535.34      221343.432    
2      197454.408    32080.93      197454.408    
3      41934.000    -9853.07       32080.93

有人能建议我采用正确的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用locwherenumpy.where替换为正值创建的掩码:

m = df['Subs'] > 0
df.loc[m, 'hrs'] = df['subtracted']
df['hrs'] = df['subtracted'].where(m, df['hrs'])
df['hrs'] = np.where(m, df['subtracted'], df['hrs'])
print (df)
   subtracted       Subs         hrs
0  281871.120  450878.77  281871.120
1  221343.432  229535.34  221343.432
2  197454.408   32080.93  197454.408
3   41934.000   -9853.07   32080.930

对于由负值创建的蒙版,可以使用mask

m = df['Subs'] < 0
df['hrs'] = np.where(m, df['hrs'], df['subtracted'])
df['hrs'] = df['subtracted'].mask(m, df['hrs'])