简体   繁体   中英

fetch value from another dataframe based on a lookup value in pandas

I have two pandas dataframes:

df1 = pd.DataFrame({'Type':list('ABCD'), 'Set':list('ZZXY')})
df2 = pd.DataFrame({'Type':list('ABCDEF'), 'Test':list('PQRSTM')})

I want to check if the values of df2['Type'] is present in df1['Type'] and if yes, then replace the corresponding value in df1['Set'] with the corresponding value from df2. So, the final df1 should like this

df1 = pd.DataFrame({'Type':list('ABCD'), 'Set':list('PQRS')}) 

Thanks

Try Merge:

import pandas as pd 

df1 = pd.DataFrame({'Type':list('ABCD'), 'Set':list('ZZXY')})
df2 = pd.DataFrame({'Type':list('ABCDEF'), 'Test':list('PQRSTM')})

df1= pd.merge(df1,df2, left_on = 'Type', right_on = 'Type', how ='left').drop('Set', axis =1)

print(df1)

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