# PyArrowとの併用

このドキュメントは、`datasets`をPyArrowと組み合わせて使用する際の簡単な入門ガイドです。特に、Arrow compute関数を用いたデータセットの処理方法、およびデータセットとPyArrow間の相互変換方法に焦点を当てています。

`datasets`は内部でPyArrowを使用しているため、ゼロコピー操作を高速に行える点が特に有用です。

## データセットの形式

デフォルトでは、datasetsは通常のPythonオブジェクト（整数、浮動小数点数、文字列、リストなど）を返します。

To get PyArrow Tables or Arrays instead, you can set the format of the dataset to `pyarrow` using [Dataset.with_format()](/docs/datasets/main/ja/package_reference/main_classes#datasets.Dataset.with_format):

```py
>>> 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"
  ]
]
```

`IterableDataset`オブジェクト（例えば`load_dataset(..., streaming=True)`を使用して取得したもの）にも適用できます。

```py
>>> 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()](/docs/datasets/main/ja/package_reference/main_classes#datasets.Dataset.map)または[Dataset.filter()](/docs/datasets/main/ja/package_reference/main_classes#datasets.Dataset.filter)でデータセットを処理する際に、Arrow compute関数を使用できます:

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

PyArrowでは、行単位ではなくバッチ単位でデータを処理する方が高速なため、`batched=True`を使用します。また、`map()`内で`batch_size=`を指定することで、各`table`のサイズを設定することも可能です。

これは[IterableDataset.map()](/docs/datasets/main/ja/package_reference/main_classes#datasets.IterableDataset.map)および[IterableDataset.filter()](/docs/datasets/main/ja/package_reference/main_classes#datasets.IterableDataset.filter)にも適用できます。

## PyArrowからのインポートまたはエクスポート

[Dataset](/docs/datasets/main/ja/package_reference/main_classes#datasets.Dataset) は PyArrow Table のラッパーであり、Table から Dataset を直接インスタンス化できます:

```python
ds = Dataset(table)
```

[Dataset.data](/docs/datasets/main/ja/package_reference/main_classes#datasets.Dataset.data) を使用して、データセットの PyArrow Table にアクセスできます。これは、Arrow データの由来と適用された操作に応じて、`MemoryMappedTable`、`InMemoryTable`、または `ConcatenationTable` を返します。

これらのオブジェクトは、`Dataset.data.table` でアクセスできる基盤となる PyArrow テーブルをラップしています。このテーブルにはデータセットのすべてのデータが含まれていますが、`Dataset._indices` に、データセットの行インデックスを PyArrow Table の行インデックスにマッピングするインデックスのマッピングが存在する場合があります。これは、[Dataset.shuffle()](/docs/datasets/main/ja/package_reference/main_classes#datasets.Dataset.shuffle) によってデータセットがシャッフルされた場合や、行の一部のみが使用されている場合（[Dataset.select()](/docs/datasets/main/ja/package_reference/main_classes#datasets.Dataset.select) の後など）に発生し得ます。

一般的なケースでは、`table = ds.with_format("arrow")[:]` を使用して、データセットを PyArrow Table にエクスポートできます。

