python-3.x - 使用 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'])
解决方案
从文档中:
- 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 |
推荐阅读
- python - 删除名称为空的列
- javascript - Outlook Addin - 是否可以通过一些 config(xml) 文件更改功能区中的加载项按钮位置
- python - 如何在 Sphinx 中引用当前类的名称?
- node.js - 如何使用 jest 在 nodejs 中模拟 redis 客户端
- scala - Spark scala:从 utcstamp 获取工作日(函数适用于特定日期,不适用于整个列)
- delphi - Delphi跨平台:如何显示类似于卸载APK时显示的通知文本?
- python - 同时获取队列中的请求
- python-3.x - 具有类继承的 kwargs 中的默认值
- swift - MapKit,用手指画线并获取坐标
- python - 使用 Flask 使用 Discord 和 Oauth2 制作 Web Dashboard 我需要帮助以将其可视化为 html