如何将pandas数据帧的hdf5二进制文件保存在内存中?

问题描述

我想获取导出为 hdf5 的 Pandas 数据帧的字节内容,理想情况下无需实际保存文件(即内存中)。

python>=3.6,< 3.9(和 pandas==1.2.4pytables==3.6.1)上,以下曾经起作用:

import pandas as pd
with pd.hdfstore(
    "in-memory-save-file",mode="w",driver="H5FD_CORE",driver_core_backing_store=0,) as store:
    store.put("my_key",df,format="table")
    binary_data = store._handle.get_file_image()

其中df是要转换为hdf5的dataframe,最后一行调用this pytables function

但是,从 python 3.9 开始,使用上面的代码段时出现以下错误

File "tables/hdf5extension.pyx",line 523,in tables.hdf5extension.File.get_file_image
tables.exceptions.HDF5ExtError: Unable to retrieve the size of the buffer for the file image.  Plese note that not all drivers provide support for image files.

错误是由上面链接的同一个 pytables 函数引发的,显然是由于 retrieving the size of the buffer for the file image 时出现的问题。不过,我不明白它的最终原因。

我尝试了其他替代方法,例如保存到 BytesIO file-object,但未成功。

如何在 python 3.9 上将 Pandas 数据帧的 hdf5 二进制文件保存在内存中?

解决方法

解决方法是执行 conda install -c conda-forge pytables 而不是 pip install pytables。不过,我仍然不明白错误背后的最终原因。