資料集文件
與 PyArrow 搭配使用
並獲得增強的文件體驗
開始使用
與 PyArrow 搭配使用
本文件簡要介紹如何將 datasets 與 PyArrow 搭配使用,特別著重於如何利用 Arrow 計算函數處理資料集,以及如何在資料集與 PyArrow 之間進行轉換。
這特別實用,因為 datasets 底層使用 PyArrow,這能實現快速的零拷貝(zero-copy)操作。
資料集格式
預設情況下,資料集會傳回一般的 Python 物件:整數、浮點數、字串、串列等。
若要取得 PyArrow Table 或 Array,您可以使用 Dataset.with_format() 將資料集格式設定為 pyarrow。
>>> from datasets import Dataset
>>> data = {"col_0": ["a", "b", "c", "d"], "col_1": [0., 0., 1., 1.]}
>>> ds = Dataset.from_dict(data)
>>> ds = ds.with_format("arrow")
>>> ds[0] # pa.Table
pyarrow.Table
col_0: string
col_1: double
----
col_0: [["a"]]
col_1: [[0]]
>>> ds[:2] # pa.Table
pyarrow.Table
col_0: string
col_1: double
----
col_0: [["a","b"]]
col_1: [[0,0]]
>>> ds["data"] # pa.array
<pyarrow.lib.ChunkedArray object at 0x1394312a0>
[
[
"a",
"b",
"c",
"d"
]
]此方法也適用於透過 load_dataset(..., streaming=True) 等方式取得的 IterableDataset 物件。
>>> ds = ds.with_format("arrow")
>>> for table in ds.iter(batch_size=2):
... print(table)
... break
pyarrow.Table
col_0: string
col_1: double
----
col_0: [["a","b"]]
col_1: [[0,0]]處理資料
PyArrow 函數通常比一般的 Python 自定義函數更快,因此它們是優化資料處理的絕佳選擇。您可以在 Dataset.map() 或 Dataset.filter() 中使用 Arrow 計算函數來處理資料集。
>>> import pyarrow.compute as pc
>>> from datasets import Dataset
>>> data = {"col_0": ["a", "b", "c", "d"], "col_1": [0., 0., 1., 1.]}
>>> ds = Dataset.from_dict(data)
>>> ds = ds.with_format("arrow")
>>> ds = ds.map(lambda t: t.append_column("col_2", pc.add(t["col_1"], 1)), batched=True)
>>> ds[:2]
pyarrow.Table
col_0: string
col_1: double
col_2: double
----
col_0: [["a","b"]]
col_1: [[0,0]]
col_2: [[1,1]]
>>> ds = ds.filter(lambda t: pc.equal(t["col_0"], "b"), batched=True)
>>> ds[0]
pyarrow.Table
col_0: string
col_1: double
col_2: double
----
col_0: [["b"]]
col_1: [[0]]
col_2: [[1]]我們使用 batched=True,因為在 PyArrow 中處理批次資料比逐列處理更快。您也可以在 map() 中使用 batch_size= 來設定每個 table 的大小。
這同樣適用於 IterableDataset.map() 與 IterableDataset.filter()。
從 PyArrow 匯入或匯出
Dataset 是 PyArrow Table 的封裝,您可以直接從 Table 實例化一個 Dataset。
ds = Dataset(table)
您可以使用 Dataset.data 來存取資料集的 PyArrow Table。根據 Arrow 資料的來源以及所套用的操作,它會回傳 MemoryMappedTable、InMemoryTable 或 ConcatenationTable。
這些物件封裝了底層的 PyArrow Table,可透過 Dataset.data.table 存取。此 Table 包含了資料集的所有資料,但也可能在 Dataset._indices 存在索引映射,用於將資料集列索引對應到 PyArrow Table 列索引。若資料集經過 Dataset.shuffle() 重新洗牌,或僅使用了資料子集(例如經過 Dataset.select()),就可能會發生這種情況。
在一般情況下,您可以使用 table = ds.with_format("arrow")[:] 將資料集匯出為 PyArrow Table。