[英]Pandas: vertical look up using two columns and two data frames
Given the following dataframes: 给定以下数据框:
df1: DF1:
ID A B
0 0 138.610513 34.860445
2 2 139.307536 34.919052
df2: DF2:
ID A B CAT
0 0 138.610513 34.860445 a
1 1 138.523152 34.807862 b
2 2 139.307536 34.919052 c
3 3 138.620263 34.883671 b
How can I look up the values in CAT
and add them to df1
as a new column? 如何在CAT
查找值并将它们作为新列添加到df1
中?
I have tried this: 我已经试过了:
df1['CAT']=df1[['A'],['B']].map(df2[['A'],['B']])
But I get: 但是我得到:
TypeError: unhashable type: 'list'
Expected output: 预期产量:
df1: DF1:
ID A B CAT
0 0 138.610513 34.860445 a
2 2 139.307536 34.919052 c
This is just a test case. 这只是一个测试案例。 In my real problem, I cannot use the IDs as a reference because they are not consistent. 在我真正的问题中,我无法使用这些ID作为参考,因为它们不一致。
Use merge
. 使用merge
。 Looks like id
too is mapped. 看起来id
也被映射。
In [4820]: df1.merge(df2)
Out[4820]:
ID A B CAT
0 0 138.610513 34.860445 a
1 2 139.307536 34.919052 c
If not, specify keys in on
, and selectively pick needed columns in df2
如果不是,请在on
指定键,然后有选择地在df2
选择所需的列
In [4825]: df1.merge(df2[['A', 'B', 'CAT']], on=['A', 'B'])
Out[4825]:
ID A B CAT
0 0 138.610513 34.860445 a
1 2 139.307536 34.919052 c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.