首页 > 解决方案 > 根据第三个数据框加入 Pandas 中的两个数据框

问题描述

我有 3 个不同尺寸的熊猫 df 。第一帧如下——

df1.head(4)

col1   col2   col3
  a      b     c
  d      e     f
  g      h     i
  j      k     l

第二帧如下——

df2.head(4)

col4   col5   col6
  m      n      o
  p      q      r
  s      t      u
  v      w      x

第三个数据帧具有col3df1col6组合df2。看起来像

df3.head(3)

col3    col6
  c       r
  i       u
  f       x

现在我想根据df3col3和中的组合组合所有三个数据框col6。结果 df 应该看起来像 -

final_df.head(3)

col1    col2    col4    col5    col2    col6
  a      b       p        q       c       r
  g      h       s        t       i       u
  d      e       v        w       f       x

我试过下面的代码

df4 = pd.merge(df1, df3, on='col3')
final_df = pd.merge(df4, df2, on='col6')

但内存错误为

MemoryError: Unable to allocate 1.79 GiB for an array with shape (2, 120193432) and data type int64

有没有其他有效的方法来做到这一点?

标签: pythonpandasdataframejoinmerge

解决方案


以上工作正常,我这边没有内存错误。我正在运行带有 32 位 python 的 8Gig Ram 计算机。

  • 为您的计算机提供更多空间
  • 检查并停止使用高内存 (Ram) 的应用程序(主要是 chrome 标签)
  • 如果上述数据框不是您使用的,则限制数据行

推荐阅读