Dataframe 互換協定#

互換協定已針對 pa.Tablepa.RecordBatch 實作,並用於在 PyArrow 與其他也實作此協定的 dataframe 程式庫之間交換資料。協定中支援的資料結構為基本資料類型加上字典資料類型。此協定也支援遺失資料,並支援分塊,意即以「批次」的列來存取資料。

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 表格

>>> 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]]