我有一个包含两组值的主数据帧:
df1 = pd.DataFrame({'id1': [1, 1, 2, 2],
'dir1': [True, False, True, False],
'value1': [55, 40, 84, 31],
'id2': [3, 3, 4, 4],
'dir2': [True, False, False, True],
'value2': [60, 30, 7, 15]})
id1 dir1 value1 id2 dir2 value2
0 1 True 55 3 True 60
1 1 False 40 3 False 30
2 2 True 84 4 False 7
3 2 False 31 4 True 15然后我有一个更新数据帧,看起来像这样:
df2 = pd.DataFrame({'id': [1, 2, 3, 4],
'value': [21, 22, 23, 24]})
id value
0 1 21
1 2 22
2 3 23
3 4 24我想用df2的新值更新df1,但只在dirX为True的情况下更新。然后,数据应如下所示:
id1 dir1 value1 id2 dir2 value2
0 1 True *21 3 True *23
1 1 False 40 3 False 30
2 2 True *22 4 False 7
3 2 False 31 4 True *24你知道这样的事情有没有可能发生?我试着查看.update,但是我不能让它工作。我是python的新手,而且只在23:00写过代码,所以可能我还不够敏锐。
发布于 2021-01-21 05:02:21
尝试使用numpy中的np.where函数。
可能是这样的:
df_1['value1'] = np.where(df_1['dir2'] == True, df_2['value'], df_1['value1'])也许您需要一些调整或合并,但我认为这将帮助您找到解决方案。
https://stackoverflow.com/questions/65817496
复制相似问题