根据条件更新两个数据框列

时间:2020-03-13 06:09:37

标签: python-3.x pandas conditional-statements

我有一个数据列,列为'PK','Column1','Column2'。 我要更新Column1和Column2如下:

If Column1 > Column2 then (Column1 = Column1 - Column2) and at the same time Column2 = 0

类似地

If Column1 < Column2 then (Column2 = Column2 - Column1) and at the same time Column1 = 0

我尝试了以下操作,但未给出预期结果:

df["Column1"] = np.where(df['Column1'] > df['Column2'], df['Column1'] - df['Column2'], 0)
df["Column2"] = np.where(df['Column1'] < df['Column2'], df['Column2'] - df['Column1'], 0)

1 个答案:

答案 0 :(得分:2)

使用DataFrame.assign避免测试代码第二行中的被覆盖的列Column1

df = pd.DataFrame({
         'Column1':[4,5,4,5,5,4],
         'Column2':[7,8,9,4,2,3],

})
print (df)
   Column1  Column2
0        4        7
1        5        8
2        4        9
3        5        4
4        5        2
5        4        3

a = np.where(df['Column1'] > df['Column2'], df['Column1'] - df['Column2'], 0)
b = np.where(df['Column1'] < df['Column2'], df['Column2'] - df['Column1'], 0)

df = df.assign(Column1 = a, Column2 = b)
print (df)
   Column1  Column2
0        0        3
1        0        3
2        0        5
3        1        0
4        3        0
5        1        0