如何vlookup值并获得正确的价值

时间:2017-12-04 06:32:35

标签: python python-3.x pandas

如何查找值并向右获取值?

Dataframe one:

   AD1   AF   GG 
0  DDA   4    2   
1  AA    1    2

Dataframe二:

    AD   FA  HH   
0   DDA  3   4
1   DD   3   4

期望(数据框3):

    AD   FA
0   DDA  3      
1   DD  NaN

有关:

df3 = pd.DataFrame(columns=['AD', 'FA'])
WE = df3.merge(df1, on='AD1', how='left')
df1['FA']=WE
#WE = df2.AD=np.where(df2.AD.isin(df1.AD1),df2.AD,np.nan)

我得到KeyError: 'AD'

1 个答案:

答案 0 :(得分:1)

似乎你需要:

df3 = df2[['AD', 'FA']].copy()
df3.FA=np.where(df2.AD.isin(df1.AD1),df3.FA,np.nan)
print (df3)
    AD   FA
0  DDA  3.0
1   DD  NaN

编辑:

print (df1)
       EW       WE      DA     dd  AA
0  cheese     fdwa  waddcv   21.0 NaN
1  cheese  dwadwad    dwad  231.0 NaN
2  cheese      dwa  waddcv    3.0 NaN

print (df2)
       AD   FA     BA  DA    daw
0  cheese  1.0  300.0   T      T
1  dwadaw  3.0  400.0  21  31232
#remove duplicates in EW and merge by different columns
df3 = df2.merge(df1.drop_duplicates('EW')[['EW']], left_on='AD', right_on='EW', how='left')
df3.FA=np.where(df2.AD.isin(df1.EW),df3.FA,np.nan)
df3 = df3[['AD','FA']]
print (df3)
       AD   FA
0  cheese  1.0
1  dwadaw  NaN

EDIT1:

df3 = df2[df2.AD.isin(df1.EW)]
df3 = df3[['AD','FA']]
print (df3)
       AD   FA
0  cheese  1.0

详情:

print (df2.AD.isin(df1.EW))
0     True
1    False
Name: AD, dtype: bool