如何在 python 中读取 34Gb stata (.dta) 文件

Gaj*_*are 0 python stata pandas

我正在尝试读取 34Gb Stata (.dta) 文件,但不断收到“MemoryError”消息,很明显我的 16Gb 内存不够用。

我尝试使用以下命令测试 11Mb Stata 文件:

dtafile = 'E:/test file.dta'
df = pd.read_stata(dtafile)
a = df.head()
print(a)
Run Code Online (Sandbox Code Playgroud)

我得到了正确的输出:

   app_id    inventor_id  ...  lagged_generality_FYnormalized       _merge
0  101985                 ...                        1.038381  matched (3)
1  102019  SCHOTTEK 2827  ...                        0.830110  matched (3)
2  102019  KUELLMER 2827  ...                        0.830110  matched (3)
3  102019   DICKNER 2827  ...                        0.830110  matched (3)
4  102562    VINEGAR 986  ...                        0.825088  matched (3)

[5 rows x 1448 columns]

Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)

但是当我对 34Gb 文件进行同样的尝试时,我收到了一条“MemoryError”消息。完整的错误消息是:

Traceback (most recent call last):
  File "C:\Users\Gaju\PycharmProjects\first project\work.py", line 8, in <module>
    df = pd.read_stata(dtafile)
  File "C:\Users\Gaju\PycharmProjects\first project\venv\lib\site-packages\pandas\util\_decorators.py", line 317, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\Gaju\PycharmProjects\first project\venv\lib\site-packages\pandas\io\stata.py", line 2021, in read_stata
    reader = StataReader(
  File "C:\Users\Gaju\PycharmProjects\first project\venv\lib\site-packages\pandas\io\stata.py", line 1172, in __init__
    self.path_or_buf = BytesIO(handles.handle.read())
MemoryError

Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)

AKX*_*AKX 7

从表面上看,Pandas 的 Stata 解析器目前总是将整个文件读入内存(并将其转换为内存流)。

\n

这显然有点回归 \xe2\x80\x93 如果我正确读取此差异,解析器以前只能使用磁盘中的文件流。

\n

编辑:巧合的是,最近有人提出了有关此问题的错误报告:https ://github.com/pandas-dev/pandas/issues/48700

\n

编辑2:我想我也可以尝试解决这个问题。https://github.com/pandas-dev/pandas/pull/48922

\n

编辑 3:四分之一年后,我的 PR 被合并到 Pandas 2.0 中。

\n