简体   繁体   中英

Update one dataframe value with another dataframe column value based on the condition

I have two dataframe say df1 and df2 .

df1:

id code remarks
1   a12  
2   b32  
3   c12

df2:

id code remarks
1   aaa12  ok
2   b32    done
3   ccc12  not ok

I want to update the df1 remarks value with df2 remarks value based on the id and code .

Here second value matches ( id-2 , code-b32 ) so update the value of remarks 'done' with df1 remarks column.

End result of df1 will be like below,

df1:

id code remarks
1   a12  
2   b32  done
3   c12

So far i tried like below, I know this is not correct, but i need something like this

df1_key = df1['id'].astype(str) + df1['code'].astype(str)
df2_key = df2['id'].astype(str) + df2['code'].astype(str)

df['flag'] = df1_key.isin(df2_key, df1['remarks']=df2['remarks'])

According to this one i tried the below also, but did n't work for me.

 df3 = df1.merge(df2[['remarks']], on=['id','code'], how='left')

Use DataFrame.merge with filtered columns by list:

df3 = df1[['id','code']].merge(df2, on=['id','code'], how='left')

Or by DataFrame.drop :

df3 = df1.drop('remarks', axis=1).merge(df2, on=['id','code'], how='left')

print (df3)
   id code remarks
0   1  a12     NaN
1   2  b32    done
2   3  c12     NaN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM