跳到内容

Arrow 生产者/消费者

使用 pyarrow

Polars 可以实现 Arrow 数据的零拷贝进出。这可以通过 pyarrow 或原生方式实现。让我们首先展示 pyarrow 解决方案

import polars as pl

df = pl.DataFrame({"foo": [1, 2, 3], "bar": ["ham", "spam", "jam"]})

arrow_table = df.to_arrow()
print(arrow_table)
pyarrow.Table
foo: int64
bar: large_string
----
foo: [[1,2,3]]
bar: [["ham","spam","jam"]]

或者,如果您想确保输出是零拷贝的

arrow_table_zero_copy = df.to_arrow(compat_level=pl.CompatLevel.newest())
print(arrow_table_zero_copy)
pyarrow.Table
foo: int64
bar: string_view
----
foo: [[1,2,3]]
bar: [["ham","spam","jam"]]

可以使用 pl.from_arrow 从 pyarrow 导入。

使用 Arrow PyCapsule 接口

从 Polars v1.3 及更高版本开始,Polars 实现了 Arrow PyCapsule 接口,这是一种在 Python 库之间共享 Arrow 数据的协议。

将数据从 Polars 导出到 pyarrow

要将 Polars DataFrame 转换为 pyarrow.Table,请使用 pyarrow.table 构造函数

注意

这需要 pyarrow v15 或更高版本。

import polars as pl
import pyarrow as pa

df = pl.DataFrame({"foo": [1, 2, 3], "bar": ["ham", "spam", "jam"]})
arrow_table = pa.table(df)
print(arrow_table)
pyarrow.Table
foo: int64
bar: string_view
----
foo: [[1,2,3]]
bar: [["ham","spam","jam"]]

要将 Polars Series 转换为 pyarrow.ChunkedArray,请使用 pyarrow.chunked_array 构造函数。

arrow_chunked_array = pa.chunked_array(df["foo"])
print(arrow_chunked_array)
[
  [
    1,
    2,
    3
  ]
]

您也可以将 Series 传递给 pyarrow.array 构造函数以创建连续数组。请注意,如果底层 Series 包含多个块,则这将不是零拷贝。

arrow_array = pa.array(df["foo"])
print(arrow_array)
[
  1,
  2,
  3
]

将数据从 pyarrow 导入到 Polars

我们可以使用 polars.DataFrame 构造函数将 pyarrow Table 传回 Polars

polars_df = pl.DataFrame(arrow_table)
print(polars_df)
shape: (3, 2)
┌─────┬──────┐
│ foo ┆ bar  │
│ --- ┆ ---  │
│ i64 ┆ str  │
╞═════╪══════╡
│ 1   ┆ ham  │
│ 2   ┆ spam │
│ 3   ┆ jam  │
└─────┴──────┘

类似地,我们可以使用 polars.Series 构造函数将 pyarrow ChunkedArrayArray 传回 Polars

polars_series = pl.Series(arrow_chunked_array)
print(polars_series)
shape: (3,)
Series: '' [i64]
[
    1
    2
    3
]

与其他 Arrow 库一起使用

支持 PyCapsule 接口的库的列表正在不断增长。Polars 的 SeriesDataFrame 对象可以与每个此类库自动协同工作。

致库维护者

如果您正在开发一个希望与 Polars 集成的库,建议您自行实现 Arrow PyCapsule 接口。这带来诸多好处

  • Polars Series 和 DataFrame 的零拷贝交换
  • 无需依赖 pyarrow。
  • 无需直接依赖 Polars。
  • 与将指针作为原始整数处理相比,更难导致内存泄漏。
  • 与其他支持 PyCapsule 接口的库自动实现零拷贝集成。

直接使用 Polars

Polars 还可以直接使用、导出和导入 Arrow C 数据接口。这推荐用于不支持 Arrow PyCapsule 接口且希望在不要求安装 pyarrow 的情况下与 Polars 进行互操作的库。

  • 要导出 ArrowArray C 结构体,Polars 提供了:Series._export_arrow_to_c
  • 要导入 ArrowArray C 结构体,Polars 提供了 Series._import_arrow_from_c