数据帧交换协议#

交换协议已针对 pa.Tablepa.RecordBatch 实现,用于在 PyArrow 和也实现了该协议的其他数据帧库之间交换数据。协议中支持的数据结构是原始数据类型加上字典数据类型。该协议还具有缺失数据支持,并且支持分块,这意味着以“批量”行访问数据。

Python dataframe 交换协议由 Python 数据 API 标准联盟 设计,旨在实现 Python 生态系统中 dataframe 库之间的数据交换。 有关该标准的更多信息,请参阅协议文档

从 PyArrow 到其他库:__dataframe__() 方法#

__dataframe__() 方法创建一个新的交换对象,使用者库可以获取该对象并构建自己的对象。

>>> import pyarrow as pa
>>> table = pa.table({"n_attendees": [100, 10, 1]})
>>> table.__dataframe__()
<pyarrow.interchange.dataframe._PyArrowDataFrame object at ...>

这是供使用者库在调用 from_dataframe() 函数时使用的,不应由用户手动使用。

从其他库到 PyArrow:from_dataframe()#

通过 from_dataframe() 函数,我们可以从任何实现了 __dataframe__() 方法的 dataframe 对象通过 dataframe 交换协议构建一个 pyarrow.Table

例如,我们可以使用交换协议获取 pandas dataframe 并构建一个 PyArrow table

>>> import pyarrow
>>> from pyarrow.interchange import from_dataframe

>>> import pandas as pd
>>> df = pd.DataFrame({
...         "n_attendees": [100, 10, 1],
...         "country": ["Italy", "Spain", "Slovenia"],
...     })
>>> df
   n_attendees   country
0          100     Italy
1           10     Spain
2            1  Slovenia
>>> from_dataframe(df)
pyarrow.Table
n_attendees: int64
country: large_string
----
n_attendees: [[100,10,1]]
country: [["Italy","Spain","Slovenia"]]

我们可以对 polars dataframe 执行相同的操作

>>> import polars as pl
>>> from datetime import datetime
>>> arr = [datetime(2023, 5, 20, 10, 0),
...        datetime(2023, 5, 20, 11, 0),
...        datetime(2023, 5, 20, 13, 30)]
>>> df = pl.DataFrame({
...          'Talk': ['About Polars','Intro into PyArrow','Coding in Rust'],
...          'Time': arr,
...      })
>>> df
shape: (3, 2)
┌────────────────────┬─────────────────────┐
│ Talk               ┆ Time                │
│ ---                ┆ ---                 │
│ str                ┆ datetime[μs]        │
╞════════════════════╪═════════════════════╡
│ About Polars       ┆ 2023-05-20 10:00:00 │
│ Intro into PyArrow ┆ 2023-05-20 11:00:00 │
│ Coding in Rust     ┆ 2023-05-20 13:30:00 │
└────────────────────┴─────────────────────┘
>>> from_dataframe(df)
pyarrow.Table
Talk: large_string
Time: timestamp[us]
----
Talk: [["About Polars","Intro into PyArrow","Coding in Rust"]]
Time: [[2023-05-20 10:00:00.000000,2023-05-20 11:00:00.000000,2023-05-20 13:30:00.000000]]