【发布时间】: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