Pandas 到 excel 使用 XLSX 编写器 - 常量 Memory/In 内存

Pandas to excel using XLSX Writer - Constant Memory/In Memory

我正在使用 pandas 和 xlsxwriter 在 AWS lambda 中创建 excel 报告。我一直遇到一个问题,即当创建一个 60MB 左右的相当大的 excel 文件时磁盘 space 已满,但是有 512MB 的磁盘 space 可用。

我一直在努力弄清楚发生这种情况的原因和原因,我遇到了一个看起来很有希望的 属性 我可以通过,constant_memory,所以我使用以下代码进行了尝试:

with pd.ExcelWriter(output, options={"constant_memory": True}) as writer:

这似乎确实确保了我的 lambda 始终如一地运行完成,如果我删除它,它就不再运行,但问题是我收到以下警告:

FutureWarning: Use of **kwargs is deprecated, use engine_kwargs instead.
    with pd.ExcelWriter(output, options={"constant_memory": True}) as writer:

然后我在 SO 上阅读了一篇 post,我认为这是 xlsxwriter 的作者提出的,这表明 属性 在使用 pandas 时实际上不起作用。这一点很明显,因为我只得到 excel 报告中的第一列和 360000 行的最后一行。我很困惑如何通过它来确保我的 lambda completes0?为什么如果我不通过它,那么我的 lambda 就会用完磁盘 space?

第二个奇怪的事情是 pandas 的文档根本没有提到任何称为 options 的参数,如果我尝试使用 engine_kwargs 传递 constant_memory :

with pd.ExcelWriter(output, engine_kwargs={'constant_memory': True}) as writer:

我收到以下错误:

TypeError: __init__() got an unexpected keyword argument 'constant_memory'

希望对xlsxwriter比较熟悉的朋友能帮我理解一下这几点。

xlsxwriter 的文档还提到了 属性 in_memory,这似乎可以解决我的问题,但我无法将其传递给 pd.ExcelWriter:

TypeError: __init__() got an unexpected keyword argument 'in_memory'

**编辑:传递 in_memory 确实解决了我遇到的问题,但我在使用 kwargs options.

传递它时收到弃用警告
with pd.ExcelWriter(output, options={"in_memory": True}) as writer:

FutureWarning: Use of **kwargs is deprecated, use engine_kwargs instead.
    with pd.ExcelWriter(output, options={"in_memory": True}) as writer:

如何使用 pandas 将此 属性 传递给 xlsxwriter 而不会收到弃用警告,因为它似乎可以解决我的问题?

我不是专家,反正你试过了吗

pd.ExcelWriter(output, engine_kwargs={'options': {"constant_memory": True}})

?

当您收到弃用通知时,将 xlsxwriter 选项传递给 Pandas 的正确语法是:

writer = pd.ExcelWriter('pandas_example.xlsx',
                        engine='xlsxwriter',
                        engine_kwargs={'options': {'strings_to_numbers': True}})

看到这个section of the XlsxWriter docs

但是,正如您在问题中指出的那样,根据您的观察,constant_memory 选项不适用于 Pandas,因为它需要数据按行顺序写入,但 Pandas 使用按列顺序写入。

但是,需要明确的是,constant_memory 选项只会减少您的应用程序使用的“内存”。它不会使文件变小(实际上,如果文件包含大量字符串数据,它通常会使文件变大)。它可能只能通过“解决”您的问题,因为它只将一列数据写入文件,因此文件比预期的要小得多。