python - Pandas:有没有比 merge() 更高效的方法来连接其他 Dataframe 的几列?
问题描述
我有一种情况,我需要获取另一个 Dataframe 的 2 列并将它们加入到第一个 Dataframe 中,基于像外键这样的过滤器。
Frame1
column1 column2 column3 ........ column98 column99
1 7 15 John 7
2 9 32 Dale 4
3 4 25 Leon 2
Frame2
columnA columnB columnC columnD columnE
1 Leon 24 13 6
1 Nicolas 19 12 4
1 Albert 32 34 9
1 Dale 14 42 2
1 John 18 33 1
Result
column1 column2 column3 ........ column98 column99 columnD columnE
1 7 15 John 7 33 1
2 9 32 Dale 4 42 2
3 4 25 Leon 2 13 6
我这样做是为了得到这个结果:
Frame1 = Frame1.merge(Frame2[['columnB','columnD', 'columnE']], left_on = 'column98', right_on ='columnB', how='left' )
我的怀疑是因为我看到了其他方法来获取其他 DataFrame 中的列,例如查找、融化、loc,而我的 DataFrame1 有数百万行,所以我正在寻找执行此操作的最具性能的方法。
最好的问候,路易斯
解决方案
您可以利用 DataFrame 索引进行高性能合并。根据您是否有 unqiue 键,存在一些性能差异。
Frame1.set_index('column98', inplace=True)
Frame1.sort_index(inplace=True)
Frame2.set_index('columnB', inplace=True)
Frame.sort_index(inplace=True)
推荐阅读
- node.js - 查找一个并按 objectId 更新嵌套数组
- vue.js - Vue.js - 淡入不工作,但淡出正在工作 v-show
- node.js - 在 AWS Lambda 中将流通过管道传输到 S3 PutObject
- javascript - Chartjs Plugin Annotation 不起作用(已注册)
- java - 两个 webproject esapi 错误:未通过 ESAPI 验证配置设置所选类型
- r - 跨越(分解)数据框中的所有日期
- flutter - 为什么在使用第二个文本字段之前显示cubit结果?
- sql - sql总和值不同的id
- visual-studio - Git-Submodule 依赖项与 Visual Studio 依赖项
- reactjs - Vite.js + React:超出最大调用堆栈大小