[英]How to do a vlookup in pandas with different primary key and foreign key column names in two dataframes?
Lets say we have two dataframes df and df1 with different column names like sku as primary key and sno as its foreign key:假设我们有两个数据帧 df 和 df1,它们具有不同的列名,例如 sku 作为主键,sno 作为外键:
Example1(df)
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(df1)
sno dept
113 a
122 b
123 b
301 c
I want to do a join or merge which looks like this:我想做一个像这样的连接或合并:
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
Unfortunately df.merge(df1, on='sku', how='left')
and df['dept']=df.sku.map(df1.dept)
doesn't work.不幸的是
df.merge(df1, on='sku', how='left')
和df['dept']=df.sku.map(df1.dept)
不起作用。
Example modified from: vlookup in Pandas using join示例修改自: vlookup in Pandas using join
you have to set the left and right key你必须设置左右键
df1.merge(df2, right_on='sno',left_on='sku',how='left')
sku loc flag sno dept
0 122 61 True 122 b
1 123 61 True 123 b
2 113 62 True 113 a
3 122 62 True 122 b
4 123 62 False 123 b
5 122 63 False 122 b
6 301 63 True 301 c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.