Python 通过比较列连接DataFrame

Python 通过比较列连接DataFrame,python,pandas,dataframe,join,Python,Pandas,Dataframe,Join,我有两个数据帧: df1: df2: 我希望更新df1的列“D”,这样,如果df2的列D的值小于相同值“a”和“B”,则该行的列df.D将替换df1.D 预期产出为: 有人能帮我翻译一下python代码吗 谢谢。请共享数据,不要图片共享数据,不要图片 df_new=pd.merge(df1,df2, how='left', on=['A','B'],suffixes=('', '_r'))#merge the two frames on A and B and suffix df2['D'

我有两个数据帧:

df1:

df2:

我希望更新df1的列“D”,这样,如果df2的列D的值小于相同值“a”和“B”,则该行的列df.D将替换df1.D

预期产出为:

有人能帮我翻译一下python代码吗


谢谢。

请共享数据,不要图片共享数据,不要图片
df_new=pd.merge(df1,df2, how='left', on=['A','B'],suffixes=('', '_r'))#merge the two frames on A and B and suffix df2['D'] WITH R
df_new['D']=np.where(df_new['D']>df_new['D_r'],df_new['D_r'],df_new['D'])#Use np.where to replace column D with the right value as per condition
df_new.drop('D_r',1, inplace=True)#Drop the D_r column



   A  B    C    D
0  x  2    f  1.0
1  x  3    2  1.0
2  y  2    4  3.0
3  y  5  dfs  2.0
4  z  1  sds  5.0