2个Pandas数据框之间的vlookup [英] vlookup between 2 Pandas dataframes

查看:216
本文介绍了2个Pandas数据框之间的vlookup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个pandas数据框,如下所示.

I have 2 pandas Dataframes as follows.

DF1:

Security     ISIN
ABC           I1 
DEF           I2
JHK           I3
LMN           I4
OPQ           I5

和DF2:

ISIN      Value
 I2        100
 I3        200
 I5        300

我想得到第三个数据帧,如下所示:

I would like to end up with a third dataframe looking like this:

DF3:

Security   Value
 DEF       100
 JHK       200
 OPQ       300

推荐答案

您可以使用 merge ,默认情况下是内部联接,因此how=inner被省略,并且如果两个Dataframes中只有一个公共列,则还可以省略参数on='ISIN': >

You can use merge, by default is inner join, so how=inner is omit and if there is only one common column in both Dataframes, you can also omit parameter on='ISIN':

df3 = pd.merge(df1, df2)
#remove column ISIN
df3.drop('ISIN', axis=1, inplace=True)
print (df3)
  Security  Value
0      DEF    100
1      JHK    200
2      OPQ    300

map ISIN来自df1Series:

print (df1.set_index('ISIN')['Security'])
ISIN
I1    ABC
I2    DEF
I3    JHK
I4    LMN
I5    OPQ
Name: Security, dtype: object

#create new df by copy of df2
df3 = df2.copy()
df3['Security'] = df3.ISIN.map(df1.set_index('ISIN')['Security'])
#remove column ISIN
df3.drop('ISIN', axis=1, inplace=True)
#change order of columns
df3 = df3[['Security','Value']]
print (df3)
  Security  Value
0      DEF    100
1      JHK    200
2      OPQ    300

这篇关于2个Pandas数据框之间的vlookup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆