一条研究流水线会让同一批价格经过四个库:PyArrow 读文件,Polars 清洗,pandas 喂给模型,DuckDB 回答查询。如果每次交接都要转换数据,流水线大部分时间和内存都花在制造副本上。以 Arrow 作为共同布局,交接可以只是一个指针:下一个库看的是完全相同的那些字节。
用通俗的话说这个想法
我们在哪里。 主题 4 说明数组是几块布局固定的缓冲区。这个主题是它的回报:理解该布局的库可以直接使用这些缓冲区。DuckDB 技能展示了查询这一侧;这里的重点是通过比较缓冲区地址来证明确实没有发生拷贝。
在库或函数之间传递数据时,让接收方读取发送方的内存而不是副本。十行和一百亿行的成本相同,并且共享的数据是只读的,因为任何修改都会被所有人看到。
用地址来证明
buffers()[1].address 是 close 数组的值在内存中的起始位置。numpy_view 返回的 NumPy 数组,其数据指针正是同一个数字:同样的字节,没有拷贝,NumPy 因为不拥有这块内存而把它标为只读。Polars 对数值列也是这样处理。当某个转换必须拷贝时,例如含空值的列,Arrow 会报错而不是悄悄拷贝。
# A NumPy array over the closes: same address as the Arrow buffer, read-onlyimport pyarrow.compute as pcview = numpy_view(table, "close")print(type(view).__name__, view.dtype, "| writeable:", view.flags.writeable)print("same bytes as the Arrow buffer:", view.__array_interface__["data"][0] == close.buffers()[1].address)
ndarray float64 | writeable: False same bytes as the Arrow buffer: True
# Polars on the same buffers; the sum computed from either side agreesframe = polars_view(table)print(type(frame).__name__, frame.shape)print("close buffer shared with Polars:", frame["close"].to_arrow().buffers()[1].address == close.buffers()[1].address)print(frame["volume"].sum(), pc.sum(table["volume"]).as_py())
DataFrame (33493, 7) close buffer shared with Polars: True 3398140608402 3398140608402
pandas:共享,或转换并拷贝
pandas 传统上把列存成 NumPy 数组、把字符串存成 Python 对象,所以简单的 to_pandas() 会复制每一列。使用 types_mapper=pd.ArrowDtype 时,DataFrame 的列仍是 Arrow 数组,并共享缓冲区。代价是 pandas 的某些功能默认需要 NumPy,所以在内存成为问题的地方再用它。最后是 DuckDB,它完全不需要转换:注册 Arrow 表,它就在原地扫描。
# A plain to_pandas() copies into NumPy; with Arrow dtypes the buffer is sharedplain = table.to_pandas()arrow_backed = pandas_arrow(table)print("default to_pandas shares memory :", plain["close"].values.__array_interface__["data"][0] == close.buffers()[1].address)print("Arrow-backed shares memory :", arrow_backed["close"].array.__arrow_array__().chunk(0).buffers()[1].address == close.buffers()[1].address)print(arrow_backed.dtypes.tolist()[:3])
default to_pandas shares memory : False Arrow-backed shares memory : True [string[pyarrow], date32[day][pyarrow], double[pyarrow]]
# DuckDB scans the Arrow table where it is, with no load stepprint("total volume:", duckdb_total(table, "volume"))print("matches Arrow's own sum:", duckdb_total(table, "volume") == pc.sum(table["volume"]).as_py())
total volume: 3398140608402 matches Arrow's own sum: True
大家看到的是同样的字节,如果某个库往里写,所有人的数据都会被改变。来自 Arrow 的 NumPy 视图是只读的,需要可修改的数据时,用显式、可见的 copy()。流水线原则:读取时共享,必须修改时有意识地拷贝。
任务要求
- 1`numpy_view` 与 `polars_view`
table[column].chunk(0).to_numpy(zero_copy_only=True);pl.from_arrow(table)。 - 2`pandas_arrow`
table.to_pandas(types_mapper=pd.ArrowDtype)。 - 3`duckdb_total`
con.register("t", table),然后对加引号的列名执行SELECT sum("column") FROM t,读取唯一的值。
to_numpy(zero_copy_only=True) 在含空值的列上报错。应该怎样理解?实验:评分内容
4 个任务 · 100 分- NumPy 视图:
numpy_view25 分 - 交给 Polars:
polars_view25 分 - 基于 Arrow 的 pandas:
pandas_arrow25 分 - DuckDB 就地读取:
duckdb_total25 分