执行pandas.merge()时系统冻结

时间:2014-11-13 15:20:15

标签: python pandas merge

我在4GB RAM上运行Win7 64Bit。我将一个大数据文件(3Mio行读取)读入一个Pandas数据帧,做几个isin() - 操作并获得另外两个数据帧df1和df2,每个数据帧有300000行。直到这里一切都很好,总内存消耗约为40%。但是,当我尝试合并df1和df2时,RAM消耗直接上升到几乎100%并且系统冻结结果。看起来像是内存泄漏。谁有人观察silimar?在pandas.merge()的屋顶下会发生什么导致这种情况?有没有可能让代码运行?合并命令:

merged=pandas.merge(df1, df2, on=['call/put','expiration'], how='inner', left_index=True, right_index=True)

1 个答案:

答案 0 :(得分:0)

您可能需要提供一些示例数据。我怀疑你的加入是多对一的。我尝试设置一个包含6列的示例,并且我能够在大约2分钟内在MBP上创建50,000,000条记录。

我在Ipython笔记本中运行,因此我使用了单元魔法%% time来计算单元格的运行时间。

这是我的例子:

%%time
np.random.seed(1)
n=50000000 #50,000,000
df1 = pd.DataFrame(randn(n), index=pd.date_range('1/1/2000', periods=n))
df1.columns = ['thing1']
df1['thing2'] = randn(n)
df1['thing3'] = randn(n)
df1['thing4'] = randn(n)
df1['call/put'] = np.random.choice(['put','call'], n)
df1['expiration'] = pd.date_range('1/1/2001', periods=n)

df2 = pd.DataFrame(randn(n), index=pd.date_range('1/1/2000', periods=n))
df2.columns = ['thing1']
df2['thing2'] = randn(n)
df2['thing3'] = randn(n)
df2['thing4'] = randn(n)
df2['call/put'] = np.random.choice(['put','call'], n)
df2['expiration'] = pd.date_range('1/1/2001', periods=n)

我的盒子大概需要40秒。

print df1.head()
print df2.head()

             thing1    thing2    thing3    thing4 call/put expiration
2000-01-01  1.624345 -1.139160 -1.226383 -0.157804     call 2001-01-01
2000-01-02 -0.611756 -0.082128 -0.982924  0.254592     call 2001-01-02
2000-01-03 -0.528172 -1.601699  0.457530 -0.671379      put 2001-01-03
2000-01-04 -1.072969  0.496285 -1.747807  0.181793      put 2001-01-04
2000-01-05  0.865408 -1.481422 -0.435733  1.582169     call 2001-01-05
              thing1    thing2    thing3    thing4 call/put expiration
2000-01-01 -0.020954  0.054025  2.502060  1.011011     call 2001-01-01
2000-01-02  0.635003 -1.757002 -0.311092  1.469307     call 2001-01-02
2000-01-03  1.547721  0.267789 -2.703976  0.671766      put 2001-01-03
2000-01-04 -1.288127 -0.745521  0.614661  0.897899     call 2001-01-04
2000-01-05  0.094685 -0.451766 -0.012700 -0.641612      put 2001-01-05

然后我进行合并:

%%time
merged=pd.merge(df1, df2, on=['call/put','expiration'], how='inner', left_index=True, right_index=True)

CPU times: user 20.3 s, sys: 19 s, total: 39.3 s
Wall time: 1min 58s

那么您的真实数据和虚拟示例之间可能有什么不同?