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

use*_*418 5 python merge pandas

我在 4GB RAM 上运行 Win7 64Bit。我将一个大数据文件(要读取的 3Mio 行)读入 Pandas 数据帧,执行多个 isin()-Operations 并获得 2 个其他数据帧 df1 和 df2,每个数据帧有 300000 行。直到这里一切正常,总内存消耗约为 40%。但是,当我尝试合并 df1 和 df2 时,RAM 消耗直接上升到几乎 100% 并导致系统冻结。看起来像内存泄漏。有人在观察类似的东西吗?在 pandas.merge() 的屋顶下会发生什么导致这种情况?有没有可能让代码运行?合并命令:

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

JD *_*ong 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)
Run Code Online (Sandbox Code Playgroud)

在我的盒子上大约需要 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
Run Code Online (Sandbox Code Playgroud)

然后我进行合并:

%%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
Run Code Online (Sandbox Code Playgroud)

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