首页 > 解决方案 > 使用 Pandas 合并(或加入)多列的 Vlookup

问题描述

我正在尝试在 Pandas 中做一个相当于 vLookup 的 excel。

我尝试了在这里找到的各种迭代:vlookup in Pandas using join但它似乎不起作用。

我有两个数据框,有一个公共字段“itemID”。我希望将第一个数据框中的项目特征归因于第二个数据框。

我在下面展示了我想要实现的示例代码。有人可以帮忙吗?

# test code to ask other people

res1_ = [['SABR', 'Cat1', '2y10y', 'A001'], ['SABR', 'Cat1', '5y30y', 'A002'], ['Vasicek', 'Cat1', '2y10y', 'A003'], ['LMM', 'Cat1', '2y10y', 'A004']]
df1 = pd.DataFrame(res1_, columns = ['Model', 'Type', 'Pair', 'itemID'])

res2_ = [['A001', 'Vega'], ['A003', 'Delta'], ['A001', 'Gamma'], ['A002', 'Vega'], ['A002', 'Delta'], ['A006', 'Delta']]
df2 = pd.DataFrame(res2_, columns = ['itemID', 'Metric'])

display(df1)
display(df2)
print('this is not what I want')
display(df2.merge(df1, on = 'itemID', how = 'outer'))

print('this is what I would like to get')
res3_ = [['A001', 'Vega', 'SABR', 'Cat1', '2y10y'], ['A003', 'Delta', 'Vasicek', 'Cat1', '2y10y'], ['A001', 'Gamma', 'SABR', 'Cat1', '2y10y'],\
         ['A002', 'Vega', 'SABR', 'Cat1', '5y30y'], ['A002', 'Delta', 'SABR', 'Cat1', '5y30y'], ['A006', 'Delta']]
pd.DataFrame(res3_, columns = ['itemID', 'Metric', 'Model', 'Type', 'Pair'])

标签: python-3.xexcelpandasvlookup

解决方案


文档中:

  • left:仅使用左帧中的键,类似于 SQL 左外连接;保留密钥顺序。
  • 外部:使用来自两个帧的键并集,类似于 SQL 完全外部联接;按字典顺序对键进行排序。

因此,您的合并操作应该这样编写:

 df2.merge(df1,on=['itemID'],how='left')

输出

|    | itemID   | Metric   | Model   | Type   | Pair   |
|---:|:---------|:---------|:--------|:-------|:-------|
|  0 | A001     | Vega     | SABR    | Cat1   | 2y10y  |
|  1 | A003     | Delta    | Vasicek | Cat1   | 2y10y  |
|  2 | A001     | Gamma    | SABR    | Cat1   | 2y10y  |
|  3 | A002     | Vega     | SABR    | Cat1   | 5y30y  |
|  4 | A002     | Delta    | SABR    | Cat1   | 5y30y  |
|  5 | A006     | Delta    | nan     | nan    | nan    |

推荐阅读