【问题标题】:Pandas: Is there a more performatic method to join few columns of other Dataframe than merge()?Pandas:有没有比 merge() 更高效的方法来连接其他 Dataframe 的几列?
【发布时间】:2021-03-15 15:24:58
【问题描述】:

我有一种情况,我需要获取另一个 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 有数百万行,所以我正在寻找执行此操作的最高性能的方法。

最好的问候, 路易斯

【问题讨论】:

  • 合并是非常高效的 AFAIK 和非常通用的解决方案。如果您在某些特殊情况下,例如在您希望为 M:1(或 1:1)的一列上连接,那么您 可以 map 获得与 @ 相同的输出987654324@合并。

标签: python pandas dataframe etl


【解决方案1】:

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

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

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

【讨论】:

  • 如果我放了这个索引,我需要在我的 merge() 方法中改变一些东西,还是方法、签名和参数都一样?
  • 如果索引在两个 DataFrame 中具有相同的名称,那么您不需要指定任何合并参数 iirc。在索引具有不同名称的特定情况下,您可以指定 left_index=True,right_index=True。如果你让left_on=right_on= 保持原样,我不是 100% 会发生什么。文件似乎表明它可以是一个索引名称,但我的直觉说不是
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
相关资源
最近更新 更多