将 Pandas DataFrame 序列化为内存缓冲区表示

Serialize Pandas DataFrame to in-memory buffer representation

将 DataFrame 序列化为内存中表示形式的最快方法是什么?根据一些研究,Apache Feather 格式似乎是大多数指标中最快的可用格式。

我的目标是获取 DataFrame 的序列化字节 - Feather 的唯一问题是我想避免写入磁盘和从磁盘加载的开销,而 Feather API 似乎只允许文件 I/O。是否有我应该为此研究的不同格式,或者是否有 Python 到 "fake" 文件的方法,迫使 Feather 改为写入内存缓冲区?

pyarrow 提供 BufferOutputStream 用于写入内存而不是文件。与文档字符串相比,read_featherwrite_feather 还支持从内存读取/写入编写器接口。

通过下面的代码,你可以在不进入文件系统的情况下将一个DataFrame序列化到内存中,然后直接重新构造它。

from pyarrow.feather import read_feather, write_feather
import pandas as pd
import pyarrow as pa

df = pd.DataFrame({"column": [1, 2]})
output_stream = pa.BufferOutputStream()
write_feather(df, output_stream)
df_reconstructed = read_feather(output_stream.getvalue())