首页 > 解决方案 > Pandas 合并在大型数据帧上很慢

问题描述

我有 4 个熊猫数据框(每个 3200 万行)。我想以这样一种方式连接这些数据帧,即合并的数据帧只有从所有数据帧中添加的新变量。

例如:

df1 = pd.DataFrame(data = {'col1' : [1, 2, 3],
                           'col2' : [10, 11, 12], 'col3' : [1, 1, 2], 'col4' : [100, 200, 300]})

df1

   col1  col2  col3  col4
0     1    10     1   100
1     2    11     1   200
2     3    12     2   300

df2 = pd.DataFrame(data = {'col1' : [1, 2, 3],
                           'col2' : [10, 11, 12], 'col3' : [1, 1, 2], 'col5' : [20, 40, 60]})

   col1  col2  col3  col5
0     1    10     1    20
1     2    11     1    40
2     3    12     2    60

df3 = pd.DataFrame(data = {'col1' : [1, 2, 3],
                           'col2' : [10, 11, 12], 'col3' : [1, 1, 2], 'col6' : [90, 100, 110]})

   col1  col2  col3  col6
0     1    10     1    90
1     2    11     1    100
2     3    12     2    100

我预期的输出数据框:

   col1  col2  col3   col4  col5 col6
0     1    10     1  100.0   20   90
1     2    11     1  200.0   40   100
2     3    12     2  300.0   60   110

我尝试了下面的代码,它工作得很好,但速度很慢(因为我的数据框很大)

df_merge=df1.merge(df2.merge(df3))
print(df_merge)

   col1  col2  col3  col4  col5  col6
0     1    10     1   100    20   90
1     2    11     1   200    40   100
2     3    12     2   300    60   110

有没有任何有效的方法来做同样的事情。

标签: python-3.xpandas

解决方案


我不知道它是否值得,但我听说过modin,它是大数据集的熊猫: https ://github.com/modin-project/modin


推荐阅读