简体   繁体   English

如何在两个数据框中使用不同的主键和外键列名称在 pandas 中进行 vlookup?

[英]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.

相关问题 如何在pydatatable中加入具有不同键列名称的两个数据框? - How to join two dataframes with different key column names in pydatatable? 如何在 Python Pandas 中合并两个数据帧,其中关键列名称不同,但想要从第二个数据帧中检索某些列? - How to merge two dataframes in Python Pandas, where key column names different, but want to retrieve SOME of the columns from second dataframe? 使用不同的列名连接 Pandas 中的两个数据框 - Joining Two Dataframes in Pandas With Different Column Names 如何使用熊猫组合两个数据框并具有唯一的关键列? - How to combine two dataframes and have unique key column using Pandas? 如何在两个 CSV 文件中找到所有可能的列集作为主键和外键候选者? - How to find all possible column sets as primary key & foreign key candidates in two CSV files? 比较两个具有不同列名的熊猫数据框并找到匹配项 - comparing two pandas dataframes with different column names and finding match 合并两个具有相同列名但在pandas中具有不同列数的数据帧 - Merging two dataframes with same column names but different number of columns in pandas 使用共享列值作为pandas中的键组合两个数据框 - Combining two dataframes using shared column values as key in pandas 合并两个具有不同数量的关键元素的数据框 - Merging two DataFrames with different number of key elements in Pandas 如何基于一行中的值和不同的列名合并两个熊猫数据帧? - How to merge two pandas dataframes based on a value in one row and with different column names?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM