【问题标题】:Vlookup using Pandas Merge (or Join) with multiple columns使用 Pandas 合并(或加入)多列的 Vlookup
【发布时间】:2020-07-16 16:44:00
【问题描述】:

我正在尝试在 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.x excel pandas vlookup


    【解决方案1】:

    来自documentation

    • left:仅使用左帧中的键,类似于 SQL 左外连接;保留密钥顺序。
    • outer:使用两个框架中的键并集,类似于 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    |
    

    【讨论】:

    • 感谢@sebastien D,我意识到我的问题有点不完整。我有(不幸的是)多行相同的数据(res1_ 可能有几行重复)......因此代码也会生成多行......有没有办法解决这个问题?
    猜你喜欢
    • 2019-11-04
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    相关资源
    最近更新 更多