首页 > 解决方案 > 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 有数百万行,所以我正在寻找执行此操作的最具性能的方法。

最好的问候,路易斯

标签: pythonpandasdataframeetl

解决方案


您可以利用 DataFrame 索引进行高性能合并。根据您是否有 unqiue 键,存在一些性能差异。

Frame1.set_index('column98', inplace=True)
Frame1.sort_index(inplace=True)

Frame2.set_index('columnB', inplace=True)
Frame.sort_index(inplace=True)

推荐阅读