Datasets documentation

Pandas との併用

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v4.8.4).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Pandas との併用

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

これは特に有用です。datasetsは内部でPyArrowを使用しており、PyArrowはPandasと密接に統合されているため、高速な操作が可能になるためです。

データセットの形式

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

To get Pandas DataFrames or Series instead, you can set the format of the dataset to pandas using Dataset.with_format():

>>> 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("pandas")
>>> ds[0]       # pd.DataFrame
  col_0  col_1
0     a    0.0
>>> ds[:2]      # pd.DataFrame
  col_0  col_1
0     a    0.0
1     b    0.0
>>> ds["data"]  # pd.Series
0    a
1    b
2    c
3    d
Name: col_0, dtype: object

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

>>> ds = ds.with_format("pandas")
>>> for df in ds.iter(batch_size=2):
...     print(df)
...     break
  col_0  col_1
0     a    0.0
1     b    0.0

データを処理する

Pandasの関数は、手書きの通常のPython関数よりも一般的に高速であり、データ処理の最適化に優れた選択肢です。Dataset.map()またはDataset.filter()内でPandasの関数を使用してデータセットを処理できます:

>>> 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("pandas")
>>> ds = ds.map(lambda df: df.assign(col_2=df.col_1 + 1), batched=True)
>>> ds[:2]
  col_0  col_1  col_2
0     a    0.0    1.0
1     b    0.0    1.0
>>> ds = ds.filter(lambda df: df.col_0 == "b", batched=True)
>>> ds[0]
  col_0  col_1  col_2
0     b    0.0    1.0

batched=True を使用するのは、Pandas でデータをバッチ単位で処理する方が、行単位で処理するよりも高速だからです。また、map() で batch_size= を指定することで、各 df のサイズを設定することも可能です。

これはIterableDataset.map()およびIterableDataset.filter()にも適用できます。

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

Pandasからデータをインポートするには、Dataset.from_pandas()を使用できます:

ds = Dataset.from_pandas(df)

And you can use Dataset.to_pandas() to export a Dataset to a Pandas DataFrame:

df = Dataset.to_pandas()
Update on GitHub