資料集文件

與 Pandas 搭配使用

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

與 Pandas 一起使用

本文件是關於如何將 datasets 與 Pandas 結合使用的快速入門介紹,特別著重於如何利用 Pandas 函式處理資料集,以及如何在資料集與 Pandas 之間進行轉換。

這非常實用,因為它能實現快速運算;datasets 在底層使用了 PyArrow,而 PyArrow 與 Pandas 的整合度極佳。

資料集格式

預設情況下,資料集會傳回一般的 Python 物件:整數、浮點數、字串、串列等。

若要取得 Pandas DataFrames 或 Series,您可以使用 Dataset.with_format() 將資料集格式設定為 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[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

此方法也適用於透過 load_dataset(..., streaming=True) 等方式取得的 IterableDataset 物件。

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

而您可以使用 Dataset.to_pandas() 將 Dataset 匯出為 Pandas DataFrame

df = Dataset.to_pandas()
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.