首页 > 解决方案 > 大型 RAM 机器上的 pandas 内存错误,但在较小的 RAM 机器上没有:相同的代码,相同的数据

问题描述

我在我的两台机器上运行以下命令:

import os, sqlite3
import pandas as pd
from feat_transform import filter_anevexp
db_path = r'C:\Users\timregan\Desktop\anondb_280718.sqlite3'
db = sqlite3.connect(db_path)
anevexp_df = filter_anevexp(db, 0)

在我的笔记本电脑(具有 8GB 的​​ RAM)上,它可以毫无问题地运行(尽管调用filter_anevexp需要几分钟)。在我的桌面(具有 128GB 的​​ RAM)上,它在 pandas 中失败并出现内存错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\timregan\source\MentalHealth\code\preprocessing\feat_transform.py", line 171, in filter_anevexp
    anevexp_df = anevexp_df[anevexp_df["user_id"].isin(df)].copy()
  File "C:\Users\timregan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\frame.py", line 2682, in __getitem__
    return self._getitem_array(key)
  File "C:\Users\timregan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\frame.py", line 2724, in _getitem_array
    return self._take(indexer, axis=0)
  File "C:\Users\timregan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\generic.py", line 2789, in _take
    verify=True)
  File "C:\Users\timregan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\internals.py", line 4539, in take
    axis=axis, allow_dups=True)
  File "C:\Users\timregan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\internals.py", line 4425, in reindex_indexer
    for blk in self.blocks]
  File "C:\Users\timregan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\internals.py", line 4425, in <listcomp>
    for blk in self.blocks]
  File "C:\Users\timregan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\internals.py", line 1258, in take_nd
    allow_fill=True, fill_value=fill_value)
  File "C:\Users\timregan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\algorithms.py", line 1655, in take_nd
    out = np.empty(out_shape, dtype=dtype)
MemoryError

我需要做些什么来防止在具有大量内存的机器上出现错误(例如寻址错误)吗?

注意我没有在filter_anevexp函数中包含代码,因为我对如何减少其内存占用的建议不感兴趣。我有兴趣了解为什么在相同数据上运行的相同代码在 128GB RAM 机器上因内存错误而失败,而在 8GB RAM 机器上却成功?

标签: pandas

解决方案


您在家用电脑上使用的是 32 位版本,这意味着您的 python 可执行文件只能访问 4gb 的内存。尝试使用 64 位而不是您当前使用的 32 位重新安装 python37。


推荐阅读