如何将 PyArrow table 转换为内存中的 csv

How to convert a PyArrow table to a in-memory csv

我正在寻找一种将 PyArrow table 转换为内存中的 csv 的方法,以便我可以将 csv 对象直接转储到数据库中。使用 pyarrow.csv.write_csv() 可以在磁盘上创建一个 csv 文件,但是是否有可能在内存中创建一个 csv 对象?我很难理解文档。非常感谢您的帮助!

是的,这是可能的。可以使用Python io module写入内存:

>>> import pyarrow as pa
>>> from pyarrow import csv
>>> import io

# Create a Table
>>> t = pa.Table.from_arrays([[1, 2, 3], ["a", "b", "c"]], ["c1", "c2"])

# Write to memory
>>> buf = io.BytesIO()
>>> csv.write_csv(t, buf, csv.WriteOptions(include_header=True))
>>> buf.seek(0)
0

# Read from memory for demo purposes
>>> csv.read_csv(buf)
pyarrow.Table
c1: int64
c2: string
----
c1: [[1,2,3]]
c2: [["a","b","c"]]