Pandas: 使用两列和两个数据框进行垂直查找
Pandas: vertical look up using two columns and two data frames
给定以下数据帧:
df1:
ID A B
0 0 138.610513 34.860445
2 2 139.307536 34.919052
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
如何查找 CAT
中的值并将它们作为新列添加到 df1
?
我试过这个:
df1['CAT']=df1[['A'],['B']].map(df2[['A'],['B']])
但我得到:
TypeError: unhashable type: 'list'
预期输出:
df1:
ID A B CAT
0 0 138.610513 34.860445 a
2 2 139.307536 34.919052 c
这只是一个测试用例。在我的实际问题中,我无法将ID用作参考,因为它们不一致。
使用merge
。看起来 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
如果没有,在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
给定以下数据帧:
df1:
ID A B
0 0 138.610513 34.860445
2 2 139.307536 34.919052
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
如何查找 CAT
中的值并将它们作为新列添加到 df1
?
我试过这个:
df1['CAT']=df1[['A'],['B']].map(df2[['A'],['B']])
但我得到:
TypeError: unhashable type: 'list'
预期输出:
df1:
ID A B CAT
0 0 138.610513 34.860445 a
2 2 139.307536 34.919052 c
这只是一个测试用例。在我的实际问题中,我无法将ID用作参考,因为它们不一致。
使用merge
。看起来 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
如果没有,在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