使用 join 在 Pandas 中进行 vlookup [英] vlookup in Pandas using join
本文介绍了使用 join 在 Pandas 中进行 vlookup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 2 个数据框
I have the following 2 dataframes
Example1
sku loc flag
122 61 True
123 61 True
113 62 True
122 62 True
123 62 False
122 63 False
301 63 True
Example2
sku dept
113 a
122 b
123 b
301 c
我想使用 Pandas(或任何最好的 Python 运算符)执行合并或连接操作以生成以下数据框.
I want to perform a merge, or join opertation using Pandas (or whichever Python operator is best) to produce the below data frame.
Example3
sku loc flag dept
122 61 True b
123 61 True b
113 62 True a
122 62 True b
123 62 False b
122 63 False b
301 63 True c
Both
df_Example1.join(df_Example2,lsuffix='_ProdHier')
df_Example1.join(df_Example2,how='outer',lsuffix='_ProdHier')
不工作.我究竟做错了什么?
Aren't working. What am I doing wrong?
推荐答案
执行 left
合并,这将使用 sku
列作为要加入的列:>
Perform a left
merge, this will use sku
column as the column to join on:
In [26]:
df.merge(df1, on='sku', how='left')
Out[26]:
sku loc flag dept
0 122 61 True b
1 122 62 True b
2 122 63 False b
3 123 61 True b
4 123 62 False b
5 113 62 True a
6 301 63 True c
如果 sku
实际上是您的索引,请执行以下操作:
If sku
is in fact your index then do this:
In [28]:
df.merge(df1, left_index=True, right_index=True, how='left')
Out[28]:
loc flag dept
sku
113 62 True a
122 61 True b
122 62 True b
122 63 False b
123 61 True b
123 62 False b
301 63 True c
另一种方法是使用 map
,如果您将 sku
设置为第二个 df 的索引,那么实际上它变成了一个系列,那么代码简化为:
Another method is to use map
, if you set sku
as the index on your second df, so in effect it becomes a Series then the code simplifies to this:
In [19]:
df['dept']=df.sku.map(df1.dept)
df
Out[19]:
sku loc flag dept
0 122 61 True b
1 123 61 True b
2 113 62 True a
3 122 62 True b
4 123 62 False b
5 122 63 False b
6 301 63 True c
这篇关于使用 join 在 Pandas 中进行 vlookup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文