# Main classes

## Main classes

### DatasetInfo

#### class datasets.DatasetInfo

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/info.py#L94)

( description: str = \<factory>citation: str = \<factory>homepage: str = \<factory>license: str = \<factory>features: typing.Optional\[datasets.features.features.Features] = Nonepost\_processed: typing.Optional\[datasets.info.PostProcessedInfo] = Nonesupervised\_keys: typing.Optional\[datasets.info.SupervisedKeysData] = Nonetask\_templates: typing.Optional\[typing.List\[datasets.tasks.base.TaskTemplate]] = Nonebuilder\_name: typing.Optional\[str] = Nonedataset\_name: typing.Optional\[str] = Noneconfig\_name: typing.Optional\[str] = Noneversion: typing.Union\[str, datasets.utils.version.Version, NoneType] = Nonesplits: typing.Optional\[dict] = Nonedownload\_checksums: typing.Optional\[dict] = Nonedownload\_size: typing.Optional\[int] = Nonepost\_processing\_size: typing.Optional\[int] = Nonedataset\_size: typing.Optional\[int] = Nonesize\_in\_bytes: typing.Optional\[int] = None )

Parameters

* **description** (`str`) — A description of the dataset.
* **citation** (`str`) — A BibTeX citation of the dataset.
* **homepage** (`str`) — A URL to the official homepage for the dataset.
* **license** (`str`) — The dataset’s license. It can be the name of the license or a paragraph containing the terms of the license.
* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features), *optional*) — The features used to specify the dataset’s column types.
* **post\_processed** (`PostProcessedInfo`, *optional*) — Information regarding the resources of a possible post-processing of a dataset. For example, it can contain the information of an index.
* **supervised\_keys** (`SupervisedKeysData`, *optional*) — Specifies the input feature and the label for supervised learning if applicable for the dataset (legacy from TFDS).
* **builder\_name** (`str`, *optional*) — The name of the `GeneratorBasedBuilder` subclass used to create the dataset. Usually matched to the corresponding script name. It is also the snake\_case version of the dataset builder class name.
* **config\_name** (`str`, *optional*) — The name of the configuration derived from [BuilderConfig](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.BuilderConfig).
* **version** (`str` or [Version](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.Version), *optional*) — The version of the dataset.
* **splits** (`dict`, *optional*) — The mapping between split name and metadata.
* **download\_checksums** (`dict`, *optional*) — The mapping between the URL to download the dataset’s checksums and corresponding metadata.
* **download\_size** (`int`, *optional*) — The size of the files to download to generate the dataset, in bytes.
* **post\_processing\_size** (`int`, *optional*) — Size of the dataset in bytes after post-processing, if any.
* **dataset\_size** (`int`, *optional*) — The combined size in bytes of the Arrow tables for all splits.
* **size\_in\_bytes** (`int`, *optional*) — The combined size in bytes of all files associated with the dataset (downloaded files + Arrow files).
* **task\_templates** (`List[TaskTemplate]`, *optional*) — The task templates to prepare the dataset for during training and evaluation. Each template casts the dataset’s [Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features) to standardized column names and types as detailed in `datasets.tasks`.
* \***\*config\_kwargs** (additional keyword arguments) — Keyword arguments to be passed to the [BuilderConfig](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.BuilderConfig) and used in the [DatasetBuilder](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.DatasetBuilder).

Information about a dataset.

`DatasetInfo` documents datasets, including its name, version, and features. See the constructor arguments and properties for a full list.

Not all fields are known on construction and may be updated later.

**from\_directory**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/info.py#L304)

( dataset\_info\_dir: strfs = 'deprecated'storage\_options: typing.Optional\[dict] = None )

Parameters

* **dataset\_info\_dir** (`str`) — The directory containing the metadata file. This should be the root directory of a specific dataset version.
* **fs** (`fsspec.spec.AbstractFileSystem`, *optional*) — Instance of the remote filesystem used to download the files from.

  Deprecated in 2.9.0

  `fs` was deprecated in version 2.9.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options`.
* **storage\_options** (`dict`, *optional*) — Key/value pairs to be passed on to the file-system backend, if any.

  Added in 2.9.0

Create [DatasetInfo](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetInfo) from the JSON file in `dataset_info_dir`.

This function updates all the dynamically generated fields (num\_examples, hash, time of creation,…) of the [DatasetInfo](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetInfo).

This will overwrite all previous metadata.

Example:

Copied

```
>>> from datasets import DatasetInfo
>>> ds_info = DatasetInfo.from_directory("/path/to/directory/")
```

**write\_to\_directory**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/info.py#L213)

( dataset\_info\_dirpretty\_print = Falsefs = 'deprecated'storage\_options: typing.Optional\[dict] = None )

Parameters

* **dataset\_info\_dir** (`str`) — Destination directory.
* **pretty\_print** (`bool`, defaults to `False`) — If `True`, the JSON will be pretty-printed with the indent level of 4.
* **fs** (`fsspec.spec.AbstractFileSystem`, *optional*) — Instance of the remote filesystem used to download the files from.

  Deprecated in 2.9.0

  `fs` was deprecated in version 2.9.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options`.
* **storage\_options** (`dict`, *optional*) — Key/value pairs to be passed on to the file-system backend, if any.

  Added in 2.9.0

Write `DatasetInfo` and license (if present) as JSON files to `dataset_info_dir`.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.info.write_to_directory("/path/to/directory/")
```

### Dataset

The base class [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) implements a Dataset backed by an Apache Arrow table.

#### class datasets.Dataset

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L658)

( arrow\_table: Tableinfo: typing.Optional\[datasets.info.DatasetInfo] = Nonesplit: typing.Optional\[datasets.splits.NamedSplit] = Noneindices\_table: typing.Optional\[datasets.table.Table] = Nonefingerprint: typing.Optional\[str] = None )

A Dataset backed by an Arrow table.

**add\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L5588)

( name: strcolumn: typing.Union\[list, \<built-in function array>]new\_fingerprint: str )

Parameters

* **name** (`str`) — Column name.
* **column** (`list` or `np.array`) — Column data to be added.

Add column to Dataset.

Added in 1.7

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> more_text = ds["text"]
>>> ds.add_column(name="text_2", column=more_text)
Dataset({
    features: ['text', 'label', 'text_2'],
    num_rows: 1066
})
```

**add\_item**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L5835)

( item: dictnew\_fingerprint: str )

Parameters

* **item** (`dict`) — Item data to be added.

Add item to Dataset.

Added in 1.7

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> new_review = {'label': 0, 'text': 'this movie is the absolute worst thing I have ever seen'}
>>> ds = ds.add_item(new_review)
>>> ds[-1]
{'label': 0, 'text': 'this movie is the absolute worst thing I have ever seen'}
```

**from\_file**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L736)

( filename: strinfo: typing.Optional\[datasets.info.DatasetInfo] = Nonesplit: typing.Optional\[datasets.splits.NamedSplit] = Noneindices\_filename: typing.Optional\[str] = Nonein\_memory: bool = False )

Parameters

* **filename** (`str`) — File name of the dataset.
* **info** (`DatasetInfo`, *optional*) — Dataset information, like description, citation, etc.
* **split** (`NamedSplit`, *optional*) — Name of the dataset split.
* **indices\_filename** (`str`, *optional*) — File names of the indices.
* **in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.

Instantiate a Dataset backed by an Arrow table at filename.

**from\_buffer**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L776)

( buffer: Bufferinfo: typing.Optional\[datasets.info.DatasetInfo] = Nonesplit: typing.Optional\[datasets.splits.NamedSplit] = Noneindices\_buffer: typing.Optional\[pyarrow\.lib.Buffer] = None )

Parameters

* **buffer** (`pyarrow.Buffer`) — Arrow buffer.
* **info** (`DatasetInfo`, *optional*) — Dataset information, like description, citation, etc.
* **split** (`NamedSplit`, *optional*) — Name of the dataset split.
* **indices\_buffer** (`pyarrow.Buffer`, *optional*) — Indices Arrow buffer.

Instantiate a Dataset backed by an Arrow buffer.

**from\_pandas**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L808)

( df: DataFramefeatures: typing.Optional\[datasets.features.features.Features] = Noneinfo: typing.Optional\[datasets.info.DatasetInfo] = Nonesplit: typing.Optional\[datasets.splits.NamedSplit] = Nonepreserve\_index: typing.Optional\[bool] = None )

Parameters

* **df** (`pandas.DataFrame`) — Dataframe that contains the dataset.
* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features), *optional*) — Dataset features.
* **info** (`DatasetInfo`, *optional*) — Dataset information, like description, citation, etc.
* **split** (`NamedSplit`, *optional*) — Name of the dataset split.
* **preserve\_index** (`bool`, *optional*) — Whether to store the index as an additional column in the resulting Dataset. The default of `None` will store the index as a column, except for `RangeIndex` which is stored as metadata only. Use `preserve_index=True` to force it to be stored as a column.

Convert `pandas.DataFrame` to a `pyarrow.Table` to create a [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset).

The column types in the resulting Arrow Table are inferred from the dtypes of the `pandas.Series` in the DataFrame. In the case of non-object Series, the NumPy dtype is translated to its Arrow equivalent. In the case of `object`, we need to guess the datatype by looking at the Python objects in this Series.

Be aware that Series of the `object` dtype don’t carry enough information to always lead to a meaningful Arrow type. In the case that we cannot infer a type, e.g. because the DataFrame is of length 0 or the Series only contains `None/nan` objects, the type is set to `null`. This behavior can be avoided by constructing explicit features and passing it to this function.

Example:

Copied

```
>>> ds = Dataset.from_pandas(df)
```

**from\_dict**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L870)

( mapping: dictfeatures: typing.Optional\[datasets.features.features.Features] = Noneinfo: typing.Optional\[datasets.info.DatasetInfo] = Nonesplit: typing.Optional\[datasets.splits.NamedSplit] = None )

Parameters

* **mapping** (`Mapping`) — Mapping of strings to Arrays or Python lists.
* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features), *optional*) — Dataset features.
* **info** (`DatasetInfo`, *optional*) — Dataset information, like description, citation, etc.
* **split** (`NamedSplit`, *optional*) — Name of the dataset split.

Convert `dict` to a `pyarrow.Table` to create a [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset).

**from\_generator**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1006)

( generator: typing.Callablefeatures: typing.Optional\[datasets.features.features.Features] = Nonecache\_dir: str = Nonekeep\_in\_memory: bool = Falsegen\_kwargs: typing.Optional\[dict] = Nonenum\_proc: typing.Optional\[int] = None\*\*kwargs )

Parameters

* **generator** ( —`Callable`): A generator function that `yields` examples.
* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features), *optional*) — Dataset features.
* **cache\_dir** (`str`, *optional*, defaults to `"~/.cache/boincai/datasets"`) — Directory to cache data.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.
* **gen\_kwargs(`dict`,** *optional*) — Keyword arguments to be passed to the `generator` callable. You can define a sharded dataset by passing the list of shards in `gen_kwargs`.
* **num\_proc** (`int`, *optional*, defaults to `None`) — Number of processes when downloading and generating the dataset locally. This is helpful if the dataset is made of multiple files. Multiprocessing is disabled by default.

  Added in 2.7.0
* \***\*kwargs** (additional keyword arguments) — Keyword arguments to be passed to :`GeneratorConfig`.

Create a Dataset from a generator.

Example:

Copied

```
>>> def gen():
...     yield {"text": "Good", "label": 0}
...     yield {"text": "Bad", "label": 1}
...
>>> ds = Dataset.from_generator(gen)
```

Copied

```
>>> def gen(shards):
...     for shard in shards:
...         with open(shard) as f:
...             for line in f:
...                 yield {"line": line}
...
>>> shards = [f"data{i}.txt" for i in range(32)]
>>> ds = Dataset.from_generator(gen, gen_kwargs={"shards": shards})
```

**data**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1734)

( )

The Apache Arrow table backing the dataset.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.data
MemoryMappedTable
text: string
label: int64
----
text: [["compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .","the soundtrack alone is worth the price of admission .","rodriguez does a splendid job of racial profiling hollywood style--casting excellent latin actors of all ages--a trend long overdue .","beneath the film's obvious determination to shock at any cost lies considerable skill and determination , backed by sheer nerve .","bielinsky is a filmmaker of impressive talent .","so beautifully acted and directed , it's clear that washington most certainly has a new career ahead of him if he so chooses .","a visual spectacle full of stunning images and effects .","a gentle and engrossing character study .","it's enough to watch huppert scheming , with her small , intelligent eyes as steady as any noir villain , and to enjoy the perfectly pitched web of tension that chabrol spins .","an engrossing portrait of uncompromising artists trying to create something original against the backdrop of a corporate music industry that only seems to care about the bottom line .",...,"ultimately , jane learns her place as a girl , softens up and loses some of the intensity that made her an interesting character to begin with .","ah-nuld's action hero days might be over .","it's clear why deuces wild , which was shot two years ago , has been gathering dust on mgm's shelf .","feels like nothing quite so much as a middle-aged moviemaker's attempt to surround himself with beautiful , half-naked women .","when the precise nature of matthew's predicament finally comes into sharp focus , the revelation fails to justify the build-up .","this picture is murder by numbers , and as easy to be bored by as your abc's , despite a few whopping shootouts .","hilarious musical comedy though stymied by accents thick as mud .","if you are into splatter movies , then you will probably have a reasonably good time with the salton sea .","a dull , simple-minded and stereotypical tale of drugs , death and mind-numbing indifference on the inner-city streets .","the feature-length stretch . . . strains the show's concept ."]]
label: [[1,1,1,1,1,1,1,1,1,1,...,0,0,0,0,0,0,0,0,0,0]]
```

**cache\_files**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1754)

( )

The cache files containing the Apache Arrow table backing the dataset.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.cache_files
[{'filename': '/root/.cache/boincai/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-validation.arrow'}]
```

**num\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1772)

( )

Number of columns in the dataset.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.num_columns
2
```

**num\_rows**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1787)

( )

Number of rows in the dataset (same as [Dataset.**len**()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.__len__)).

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.num_rows
1066
```

**column\_names**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1804)

( )

Names of the columns in the dataset.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.column_names
['text', 'label']
```

**shape**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1819)

( )

Shape of the dataset (number of columns, number of rows).

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.shape
(1066, 2)
```

**unique**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1836)

( column: str ) → `list`

Parameters

* **column** (`str`) — Column name (list all the column names with [column\_names](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.column_names)).

Returns

`list`

List of unique elements in the given column.

Return a list of the unique elements in a column.

This is implemented in the low-level backend and as such, very fast.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.unique('label')
[1, 0]
```

**flatten**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1942)

( new\_fingerprint: typing.Optional\[str] = Nonemax\_depth = 16 ) → [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset)

Parameters

* **new\_fingerprint** (`str`, *optional*) — The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments.

Returns

[Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset)

A copy of the dataset with flattened columns.

Flatten the table. Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("squad", split="train")
>>> ds.features
{'answers': Sequence(feature={'text': Value(dtype='string', id=None), 'answer_start': Value(dtype='int32', id=None)}, length=-1, id=None),
 'context': Value(dtype='string', id=None),
 'id': Value(dtype='string', id=None),
 'question': Value(dtype='string', id=None),
 'title': Value(dtype='string', id=None)}
>>> ds.flatten()
Dataset({
    features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'],
    num_rows: 87599
})
```

**cast**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1987)

( features: Featuresbatch\_size: typing.Optional\[int] = 1000keep\_in\_memory: bool = Falseload\_from\_cache\_file: typing.Optional\[bool] = Nonecache\_file\_name: typing.Optional\[str] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000num\_proc: typing.Optional\[int] = None ) → [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset)

Parameters

* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features)) — New features to cast the dataset to. The name of the fields in the features must match the current column names. The type of the data must also be convertible from one type to the other. For non-trivial conversion, e.g. `str` <-> `ClassLabel` you should use [map()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.map) to update the Dataset.
* **batch\_size** (`int`, defaults to `1000`) — Number of examples per batch provided to cast. If `batch_size <= 0` or `batch_size == None` then provide the full dataset as a single batch to cast.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.
* **load\_from\_cache\_file** (`bool`, defaults to `True` if caching is enabled) — If a cache file storing the current computation from `function` can be identified, use it instead of recomputing.
* **cache\_file\_name** (`str`, *optional*, defaults to `None`) — Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name.
* **writer\_batch\_size** (`int`, defaults to `1000`) — Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running [map()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.map).
* **num\_proc** (`int`, *optional*, defaults to `None`) — Number of processes for multiprocessing. By default it doesn’t use multiprocessing.

Returns

[Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset)

A copy of the dataset with casted features.

Cast the dataset to a new set of features.

Example:

Copied

```
>>> from datasets import load_dataset, ClassLabel, Value
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.features
{'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None),
 'text': Value(dtype='string', id=None)}
>>> new_features = ds.features.copy()
>>> new_features['label'] = ClassLabel(names=['bad', 'good'])
>>> new_features['text'] = Value('large_string')
>>> ds = ds.cast(new_features)
>>> ds.features
{'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None),
 'text': Value(dtype='large_string', id=None)}
```

**cast\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2070)

( column: strfeature: typing.Union\[dict, list, tuple, datasets.features.features.Value, datasets.features.features.ClassLabel, datasets.features.translation.Translation, datasets.features.translation.TranslationVariableLanguages, datasets.features.features.Sequence, datasets.features.features.Array2D, datasets.features.features.Array3D, datasets.features.features.Array4D, datasets.features.features.Array5D, datasets.features.audio.Audio, datasets.features.image.Image]new\_fingerprint: typing.Optional\[str] = None )

Parameters

* **column** (`str`) — Column name.
* **feature** (`FeatureType`) — Target feature.
* **new\_fingerprint** (`str`, *optional*) — The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments.

Cast column to feature for decoding.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.features
{'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None),
 'text': Value(dtype='string', id=None)}
>>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good']))
>>> ds.features
{'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None),
 'text': Value(dtype='string', id=None)}
```

**remove\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2112)

( column\_names: typing.Union\[str, typing.List\[str]]new\_fingerprint: typing.Optional\[str] = None ) → [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset)

Parameters

* **column\_names** (`Union[str, List[str]]`) — Name of the column(s) to remove.
* **new\_fingerprint** (`str`, *optional*) — The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments.

Returns

[Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset)

A copy of the dataset object without the columns to remove.

Remove one or several column(s) in the dataset and the features associated to them.

You can also remove a column using [map()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.map) with `remove_columns` but the present method is in-place (doesn’t copy the data to a new dataset) and is thus faster.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.remove_columns('label')
Dataset({
    features: ['text'],
    num_rows: 1066
})
>>> ds.remove_columns(column_names=ds.column_names) # Removing all the columns returns an empty dataset with the `num_rows` property set to 0
Dataset({
    features: [],
    num_rows: 0
})
```

**rename\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2168)

( original\_column\_name: strnew\_column\_name: strnew\_fingerprint: typing.Optional\[str] = None ) → [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset)

Parameters

* **original\_column\_name** (`str`) — Name of the column to rename.
* **new\_column\_name** (`str`) — New name for the column.
* **new\_fingerprint** (`str`, *optional*) — The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments.

Returns

[Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset)

A copy of the dataset with a renamed column.

Rename a column in the dataset, and move the features associated to the original column under the new column name.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.rename_column('label', 'label_new')
Dataset({
    features: ['text', 'label_new'],
    num_rows: 1066
})
```

**rename\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2235)

( column\_mapping: typing.Dict\[str, str]new\_fingerprint: typing.Optional\[str] = None ) → [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset)

Parameters

* **column\_mapping** (`Dict[str, str]`) — A mapping of columns to rename to their new names
* **new\_fingerprint** (`str`, *optional*) — The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments.

Returns

[Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset)

A copy of the dataset with renamed columns

Rename several columns in the dataset, and move the features associated to the original columns under the new column names.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.rename_columns({'text': 'text_new', 'label': 'label_new'})
Dataset({
    features: ['text_new', 'label_new'],
    num_rows: 1066
})
```

**select\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2303)

( column\_names: typing.Union\[str, typing.List\[str]]new\_fingerprint: typing.Optional\[str] = None ) → [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset)

Parameters

* **column\_names** (`Union[str, List[str]]`) — Name of the column(s) to keep.
* **new\_fingerprint** (`str`, *optional*) — The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments.

Returns

[Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset)

A copy of the dataset object which only consists of selected columns.

Select one or several column(s) in the dataset and the features associated to them.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.select_columns(['text'])
Dataset({
    features: ['text'],
    num_rows: 1066
})
```

**class\_encode\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1867)

( column: strinclude\_nulls: bool = False )

Parameters

* **column** (`str`) — The name of the column to cast (list all the column names with [column\_names](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.column_names))
* **include\_nulls** (`bool`, defaults to `False`) — Whether to include null values in the class labels. If `True`, the null values will be encoded as the `"None"` class label.

  Added in 1.14.2

Casts the given column as [ClassLabel](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.ClassLabel) and updates the table.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("boolq", split="validation")
>>> ds.features
{'answer': Value(dtype='bool', id=None),
 'passage': Value(dtype='string', id=None),
 'question': Value(dtype='string', id=None)}
>>> ds = ds.class_encode_column('answer')
>>> ds.features
{'answer': ClassLabel(num_classes=2, names=['False', 'True'], id=None),
 'passage': Value(dtype='string', id=None),
 'question': Value(dtype='string', id=None)}
```

**\_\_len\_\_**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2352)

( )

Number of rows in the dataset.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.__len__
<bound method Dataset.__len__ of Dataset({
    features: ['text', 'label'],
    num_rows: 1066
})>
```

**\_\_iter\_\_**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2369)

( )

Iterate through the examples.

If a formatting is set with [Dataset.set\_format()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.set_format) rows will be returned with the selected format.

**iter**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2398)

( batch\_size: intdrop\_last\_batch: bool = False )

Parameters

* **batch\_size** (`int`) — size of each batch to yield.
* **drop\_last\_batch** (`bool`, default *False*) — Whether a last batch smaller than the batch\_size should be dropped

Iterate through the batches of size *batch\_size*.

If a formatting is set with \[*\~datasets.Dataset.set\_format*] rows will be returned with the selected format.

**formatted\_as**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2442)

( type: typing.Optional\[str] = Nonecolumns: typing.Optional\[typing.List] = Noneoutput\_all\_columns: bool = False\*\*format\_kwargs )

Parameters

* **type** (`str`, *optional*) — Output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means \`**getitem**“ returns python objects (default).
* **columns** (`List[str]`, *optional*) — Columns to format in the output. `None` means `__getitem__` returns all columns (default).
* **output\_all\_columns** (`bool`, defaults to `False`) — Keep un-formatted columns as well in the output (as python objects).
* \***\*format\_kwargs** (additional keyword arguments) — Keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`.

To be used in a `with` statement. Set `__getitem__` return format (type and columns).

**set\_format**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2474)

( type: typing.Optional\[str] = Nonecolumns: typing.Optional\[typing.List] = Noneoutput\_all\_columns: bool = False\*\*format\_kwargs )

Parameters

* **type** (`str`, *optional*) — Either output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default).
* **columns** (`List[str]`, *optional*) — Columns to format in the output. `None` means `__getitem__` returns all columns (default).
* **output\_all\_columns** (`bool`, defaults to `False`) — Keep un-formatted columns as well in the output (as python objects).
* \***\*format\_kwargs** (additional keyword arguments) — Keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`.

Set `__getitem__` return format (type and columns). The data formatting is applied on-the-fly. The format `type` (for example “numpy”) is used to format batches when using `__getitem__`. It’s also possible to use custom transforms for formatting using [set\_transform()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.set_transform).

It is possible to call [map()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.map) after calling `set_format`. Since `map` may add new columns, then the list of formatted columns

gets updated. In this case, if you apply `map` on a dataset to add a new column, then this column will be formatted as:

Copied

```
new formatted columns = (all columns - previously unformatted columns)
```

Example:

Copied

```
>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds.set_format(type='numpy', columns=['text', 'label'])
>>> ds.format
{'type': 'numpy',
'format_kwargs': {},
'columns': ['text', 'label'],
'output_all_columns': False}
```

**set\_transform**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2580)

( transform: typing.Optional\[typing.Callable]columns: typing.Optional\[typing.List] = Noneoutput\_all\_columns: bool = False )

Parameters

* **transform** (`Callable`, *optional*) — User-defined formatting transform, replaces the format defined by [set\_format()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.set_format). A formatting function is a callable that takes a batch (as a `dict`) as input and returns a batch. This function is applied right before returning the objects in `__getitem__`.
* **columns** (`List[str]`, *optional*) — Columns to format in the output. If specified, then the input batch of the transform only contains those columns.
* **output\_all\_columns** (`bool`, defaults to `False`) — Keep un-formatted columns as well in the output (as python objects). If set to True, then the other un-formatted columns are kept with the output of the transform.

Set `__getitem__` return format using this transform. The transform is applied on-the-fly on batches when `__getitem__` is called. As [set\_format()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.set_format), this can be reset using [reset\_format()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.reset_format).

Example:

Copied

```
>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
>>> def encode(batch):
...     return tokenizer(batch['text'], padding=True, truncation=True, return_tensors='pt')
>>> ds.set_transform(encode)
>>> ds[0]
{'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
 1, 1]),
 'input_ids': tensor([  101, 29353,  2135, 15102,  1996,  9428, 20868,  2890,  8663,  6895,
         20470,  2571,  3663,  2090,  4603,  3017,  3008,  1998,  2037, 24211,
         5637,  1998, 11690,  2336,  1012,   102]),
 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0])}
```

**reset\_format**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2551)

( )

Reset `__getitem__` return format to python objects and all columns.

Same as `self.set_format()`

Example:

Copied

```
>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds.set_format(type='numpy', columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
>>> ds.format
{'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'numpy'}
>>> ds.reset_format()
>>> ds.format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': None}
```

**with\_format**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2623)

( type: typing.Optional\[str] = Nonecolumns: typing.Optional\[typing.List] = Noneoutput\_all\_columns: bool = False\*\*format\_kwargs )

Parameters

* **type** (`str`, *optional*) — Either output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default).
* **columns** (`List[str]`, *optional*) — Columns to format in the output. `None` means `__getitem__` returns all columns (default).
* **output\_all\_columns** (`bool`, defaults to `False`) — Keep un-formatted columns as well in the output (as python objects).
* \***\*format\_kwargs** (additional keyword arguments) — Keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`.

Set `__getitem__` return format (type and columns). The data formatting is applied on-the-fly. The format `type` (for example “numpy”) is used to format batches when using `__getitem__`.

It’s also possible to use custom transforms for formatting using [with\_transform()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.with_transform).

Contrary to [set\_format()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.set_format), `with_format` returns a new [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) object.

Example:

Copied

```
>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds.format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': None}
>>> ds = ds.with_format(type='tensorflow', columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
>>> ds.format
{'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'tensorflow'}
```

**with\_transform**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2674)

( transform: typing.Optional\[typing.Callable]columns: typing.Optional\[typing.List] = Noneoutput\_all\_columns: bool = False )

Parameters

* **transform** (`Callable`, `optional`) — User-defined formatting transform, replaces the format defined by [set\_format()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.set_format). A formatting function is a callable that takes a batch (as a `dict`) as input and returns a batch. This function is applied right before returning the objects in `__getitem__`.
* **columns** (`List[str]`, `optional`) — Columns to format in the output. If specified, then the input batch of the transform only contains those columns.
* **output\_all\_columns** (`bool`, defaults to `False`) — Keep un-formatted columns as well in the output (as python objects). If set to `True`, then the other un-formatted columns are kept with the output of the transform.

Set `__getitem__` return format using this transform. The transform is applied on-the-fly on batches when `__getitem__` is called.

As [set\_format()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.set_format), this can be reset using [reset\_format()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.reset_format).

Contrary to [set\_transform()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.set_transform), `with_transform` returns a new [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) object.

Example:

Copied

```
>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> def encode(example):
...     return tokenizer(example["text"], padding=True, truncation=True, return_tensors='pt')
>>> ds = ds.with_transform(encode)
>>> ds[0]
{'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
 1, 1, 1, 1, 1]),
 'input_ids': tensor([  101, 18027, 16310, 16001,  1103,  9321,   178, 11604,  7235,  6617,
         1742,  2165,  2820,  1206,  6588, 22572, 12937,  1811,  2153,  1105,
         1147, 12890, 19587,  6463,  1105, 15026,  1482,   119,   102]),
 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0])}
```

**\_\_getitem\_\_**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2801)

( key )

Can be used to index columns (by string names) or rows (by integer index or iterable of indices or bools).

**cleanup\_cache\_files**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2811)

( ) → `int`

Returns

`int`

Number of removed files.

Clean up all cache files in the dataset cache directory, excepted the currently used cache file if there is one.

Be careful when running this command that no other process is currently using other cache files.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.cleanup_cache_files()
10
```

**map**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2858)

( function: typing.Optional\[typing.Callable] = Nonewith\_indices: bool = Falsewith\_rank: bool = Falseinput\_columns: typing.Union\[str, typing.List\[str], NoneType] = Nonebatched: bool = Falsebatch\_size: typing.Optional\[int] = 1000drop\_last\_batch: bool = Falseremove\_columns: typing.Union\[str, typing.List\[str], NoneType] = Nonekeep\_in\_memory: bool = Falseload\_from\_cache\_file: typing.Optional\[bool] = Nonecache\_file\_name: typing.Optional\[str] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000features: typing.Optional\[datasets.features.features.Features] = Nonedisable\_nullable: bool = Falsefn\_kwargs: typing.Optional\[dict] = Nonenum\_proc: typing.Optional\[int] = Nonesuffix\_template: str = '\_{rank:05d}\_of\_{num\_proc:05d}'new\_fingerprint: typing.Optional\[str] = Nonedesc: typing.Optional\[str] = None )

Parameters

* **function** (`Callable`) — Function with one of the following signatures:

  * `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` and `with_indices=False` and `with_rank=False`
  * `function(example: Dict[str, Any], *extra_args) -> Dict[str, Any]` if `batched=False` and `with_indices=True` and/or `with_rank=True` (one extra arg for each)
  * `function(batch: Dict[str, List]) -> Dict[str, List]` if `batched=True` and `with_indices=False` and `with_rank=False`
  * `function(batch: Dict[str, List], *extra_args) -> Dict[str, List]` if `batched=True` and `with_indices=True` and/or `with_rank=True` (one extra arg for each)

  For advanced usage, the function can also return a `pyarrow.Table`. Moreover if your function returns nothing (`None`), then `map` will run your function and return the dataset unchanged. If no function is provided, default to identity function: `lambda x: x`.
* **with\_indices** (`bool`, defaults to `False`) — Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx[, rank]): ...`.
* **with\_rank** (`bool`, defaults to `False`) — Provide process rank to `function`. Note that in this case the signature of `function` should be `def function(example[, idx], rank): ...`.
* **input\_columns** (`Optional[Union[str, List[str]]]`, defaults to `None`) — The columns to be passed into `function` as positional arguments. If `None`, a `dict` mapping to all formatted columns is passed as one argument.
* **batched** (`bool`, defaults to `False`) — Provide batch of examples to `function`.
* **batch\_size** (`int`, *optional*, defaults to `1000`) — Number of examples per batch provided to `function` if `batched=True`. If `batch_size <= 0` or `batch_size == None`, provide the full dataset as a single batch to `function`.
* **drop\_last\_batch** (`bool`, defaults to `False`) — Whether a last batch smaller than the batch\_size should be dropped instead of being processed by the function.
* **remove\_columns** (`Optional[Union[str, List[str]]]`, defaults to `None`) — Remove a selection of columns while doing the mapping. Columns will be removed before updating the examples with the output of `function`, i.e. if `function` is adding columns with names in `remove_columns`, these columns will be kept.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Keep the dataset in memory instead of writing it to a cache file.
* **load\_from\_cache\_file** (`Optioanl[bool]`, defaults to `True` if caching is enabled) — If a cache file storing the current computation from `function` can be identified, use it instead of recomputing.
* **cache\_file\_name** (`str`, *optional*, defaults to `None`) — Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name.
* **writer\_batch\_size** (`int`, defaults to `1000`) — Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`.
* **features** (`Optional[datasets.Features]`, defaults to `None`) — Use a specific Features to store the cache file instead of the automatically generated one.
* **disable\_nullable** (`bool`, defaults to `False`) — Disallow null values in the table.
* **fn\_kwargs** (`Dict`, *optional*, defaults to `None`) — Keyword arguments to be passed to `function`.
* **num\_proc** (`int`, *optional*, defaults to `None`) — Max number of processes when generating cache. Already cached shards are loaded sequentially.
* **suffix\_template** (`str`) — If `cache_file_name` is specified, then this suffix will be added at the end of the base name of each. Defaults to `"_{rank:05d}_of_{num_proc:05d}"`. For example, if `cache_file_name` is “processed.arrow”, then for `rank=1` and `num_proc=4`, the resulting file would be `"processed_00001_of_00004.arrow"` for the default suffix.
* **new\_fingerprint** (`str`, *optional*, defaults to `None`) — The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments.
* **desc** (`str`, *optional*, defaults to `None`) — Meaningful description to be displayed alongside with the progress bar while mapping examples.

Apply a function to all the examples in the table (individually or in batches) and update the table. If your function returns a column that already exists, then it overwrites it.

You can specify whether the function should be batched or not with the `batched` parameter:

* If batched is `False`, then the function takes 1 example in and should return 1 example. An example is a dictionary, e.g. `{"text": "Hello there !"}`.
* If batched is `True` and `batch_size` is 1, then the function takes a batch of 1 example as input and can return a batch with 1 or more examples. A batch is a dictionary, e.g. a batch of 1 example is `{"text": ["Hello there !"]}`.
* If batched is `True` and `batch_size` is `n > 1`, then the function takes a batch of `n` examples as input and can return a batch with `n` examples, or with an arbitrary number of examples. Note that the last batch may have less than `n` examples. A batch is a dictionary, e.g. a batch of `n` examples is `{"text": ["Hello there !"] * n}`.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> def add_prefix(example):
...     example["text"] = "Review: " + example["text"]
...     return example
>>> ds = ds.map(add_prefix)
>>> ds[0:3]["text"]
['Review: compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .',
 'Review: the soundtrack alone is worth the price of admission .',
 'Review: rodriguez does a splendid job of racial profiling hollywood style--casting excellent latin actors of all ages--a trend long overdue .']

# process a batch of examples
>>> ds = ds.map(lambda example: tokenizer(example["text"]), batched=True)
# set number of processors
>>> ds = ds.map(add_prefix, num_proc=4)
```

**filter**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L3532)

( function: typing.Optional\[typing.Callable] = Nonewith\_indices = Falseinput\_columns: typing.Union\[str, typing.List\[str], NoneType] = Nonebatched: bool = Falsebatch\_size: typing.Optional\[int] = 1000keep\_in\_memory: bool = Falseload\_from\_cache\_file: typing.Optional\[bool] = Nonecache\_file\_name: typing.Optional\[str] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000fn\_kwargs: typing.Optional\[dict] = Nonenum\_proc: typing.Optional\[int] = Nonesuffix\_template: str = '\_{rank:05d}\_of\_{num\_proc:05d}'new\_fingerprint: typing.Optional\[str] = Nonedesc: typing.Optional\[str] = None )

Parameters

* **function** (`Callable`) — Callable with one of the following signatures:

  * `function(example: Dict[str, Any]) -> bool` if `with_indices=False, batched=False`
  * `function(example: Dict[str, Any], indices: int) -> bool` if `with_indices=True, batched=False`
  * `function(example: Dict[str, List]) -> List[bool]` if `with_indices=False, batched=True`
  * `function(example: Dict[str, List], indices: List[int]) -> List[bool]` if `with_indices=True, batched=True`

  If no function is provided, defaults to an always `True` function: `lambda x: True`.
* **with\_indices** (`bool`, defaults to `False`) — Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`.
* **input\_columns** (`str` or `List[str]`, *optional*) — The columns to be passed into `function` as positional arguments. If `None`, a `dict` mapping to all formatted columns is passed as one argument.
* **batched** (`bool`, defaults to `False`) — Provide batch of examples to `function`.
* **batch\_size** (`int`, *optional*, defaults to `1000`) — Number of examples per batch provided to `function` if `batched = True`. If `batched = False`, one example per batch is passed to `function`. If `batch_size <= 0` or `batch_size == None`, provide the full dataset as a single batch to `function`.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Keep the dataset in memory instead of writing it to a cache file.
* **load\_from\_cache\_file** (`Optional[bool]`, defaults to `True` if caching is enabled) — If a cache file storing the current computation from `function` can be identified, use it instead of recomputing.
* **cache\_file\_name** (`str`, *optional*) — Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name.
* **writer\_batch\_size** (`int`, defaults to `1000`) — Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`.
* **fn\_kwargs** (`dict`, *optional*) — Keyword arguments to be passed to `function`.
* **num\_proc** (`int`, *optional*) — Number of processes for multiprocessing. By default it doesn’t use multiprocessing.
* **suffix\_template** (`str`) — If `cache_file_name` is specified, then this suffix will be added at the end of the base name of each. For example, if `cache_file_name` is `"processed.arrow"`, then for `rank = 1` and `num_proc = 4`, the resulting file would be `"processed_00001_of_00004.arrow"` for the default suffix (default `_{rank:05d}_of_{num_proc:05d}`).
* **new\_fingerprint** (`str`, *optional*) — The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments.
* **desc** (`str`, *optional*, defaults to `None`) — Meaningful description to be displayed alongside with the progress bar while filtering examples.

Apply a filter function to all the elements in the table in batches and update the table so that the dataset only includes examples according to the filter function.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.filter(lambda x: x["label"] == 1)
Dataset({
    features: ['text', 'label'],
    num_rows: 533
})
```

**select**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L3731)

( indices: typing.Iterablekeep\_in\_memory: bool = Falseindices\_cache\_file\_name: typing.Optional\[str] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000new\_fingerprint: typing.Optional\[str] = None )

Parameters

* **indices** (`range`, `list`, `iterable`, `ndarray` or `Series`) — Range, list or 1D-array of integer indices for indexing. If the indices correspond to a contiguous range, the Arrow table is simply sliced. However passing a list of indices that are not contiguous creates indices mapping, which is much less efficient, but still faster than recreating an Arrow table made of the requested rows.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Keep the indices mapping in memory instead of writing it to a cache file.
* **indices\_cache\_file\_name** (`str`, *optional*, defaults to `None`) — Provide the name of a path for the cache file. It is used to store the indices mapping instead of the automatically generated cache file name.
* **writer\_batch\_size** (`int`, defaults to `1000`) — Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`.
* **new\_fingerprint** (`str`, *optional*, defaults to `None`) — The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments.

Create a new dataset with rows selected following the list/array of indices.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds.select(range(4))
Dataset({
    features: ['text', 'label'],
    num_rows: 4
})
```

**sort**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L3981)

( column\_names: typing.Union\[str, typing.Sequence\[str]]reverse: typing.Union\[bool, typing.Sequence\[bool]] = Falsekind = 'deprecated'null\_placement: str = 'at\_end'keep\_in\_memory: bool = Falseload\_from\_cache\_file: typing.Optional\[bool] = Noneindices\_cache\_file\_name: typing.Optional\[str] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000new\_fingerprint: typing.Optional\[str] = None )

Parameters

* **column\_names** (`Union[str, Sequence[str]]`) — Column name(s) to sort by.
* **reverse** (`Union[bool, Sequence[bool]]`, defaults to `False`) — If `True`, sort by descending order rather than ascending. If a single bool is provided, the value is applied to the sorting of all column names. Otherwise a list of bools with the same length and order as column\_names must be provided.
* **kind** (`str`, *optional*) — Pandas algorithm for sorting selected in `{quicksort, mergesort, heapsort, stable}`, The default is `quicksort`. Note that both `stable` and `mergesort` use `timsort` under the covers and, in general, the actual implementation will vary with data type. The `mergesort` option is retained for backwards compatibility.

  Deprecated in 2.8.0

  `kind` was deprecated in version 2.10.0 and will be removed in 3.0.0.
* **null\_placement** (`str`, defaults to `at_end`) — Put `None` values at the beginning if `at_start` or `first` or at the end if `at_end` or `last`

  Added in 1.14.2
* **keep\_in\_memory** (`bool`, defaults to `False`) — Keep the sorted indices in memory instead of writing it to a cache file.
* **load\_from\_cache\_file** (`Optional[bool]`, defaults to `True` if caching is enabled) — If a cache file storing the sorted indices can be identified, use it instead of recomputing.
* **indices\_cache\_file\_name** (`str`, *optional*, defaults to `None`) — Provide the name of a path for the cache file. It is used to store the sorted indices instead of the automatically generated cache file name.
* **writer\_batch\_size** (`int`, defaults to `1000`) — Number of rows per write operation for the cache file writer. Higher value gives smaller cache files, lower value consume less temporary memory.
* **new\_fingerprint** (`str`, *optional*, defaults to `None`) — The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments

Create a new dataset sorted according to a single or multiple columns.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset('rotten_tomatoes', split='validation')
>>> ds['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>>> sorted_ds = ds.sort('label')
>>> sorted_ds['label'][:10]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> another_sorted_ds = ds.sort(['label', 'text'], reverse=[True, False])
>>> another_sorted_ds['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
```

**shuffle**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L4126)

( seed: typing.Optional\[int] = Nonegenerator: typing.Optional\[numpy.random.\_generator.Generator] = Nonekeep\_in\_memory: bool = Falseload\_from\_cache\_file: typing.Optional\[bool] = Noneindices\_cache\_file\_name: typing.Optional\[str] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000new\_fingerprint: typing.Optional\[str] = None )

Parameters

* **seed** (`int`, *optional*) — A seed to initialize the default BitGenerator if `generator=None`. If `None`, then fresh, unpredictable entropy will be pulled from the OS. If an `int` or `array_like[ints]` is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state.
* **generator** (`numpy.random.Generator`, *optional*) — Numpy random Generator to use to compute the permutation of the dataset rows. If `generator=None` (default), uses `np.random.default_rng` (the default BitGenerator (PCG64) of NumPy).
* **keep\_in\_memory** (`bool`, default `False`) — Keep the shuffled indices in memory instead of writing it to a cache file.
* **load\_from\_cache\_file** (`Optional[bool]`, defaults to `True` if caching is enabled) — If a cache file storing the shuffled indices can be identified, use it instead of recomputing.
* **indices\_cache\_file\_name** (`str`, *optional*) — Provide the name of a path for the cache file. It is used to store the shuffled indices instead of the automatically generated cache file name.
* **writer\_batch\_size** (`int`, defaults to `1000`) — Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`.
* **new\_fingerprint** (`str`, *optional*, defaults to `None`) — The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments.

Create a new Dataset where the rows are shuffled.

Currently shuffling uses numpy random generators. You can either supply a NumPy BitGenerator to use, or a seed to initiate NumPy’s default random generator (PCG64).

Shuffling takes the list of indices `[0:len(my_dataset)]` and shuffles it to create an indices mapping. However as soon as your [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) has an indices mapping, the speed can become 10x slower. This is because there is an extra step to get the row index to read using the indices mapping, and most importantly, you aren’t reading contiguous chunks of data anymore. To restore the speed, you’d need to rewrite the entire dataset on your disk again using [Dataset.flatten\_indices()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.flatten_indices), which removes the indices mapping.

This may take a lot of time depending of the size of your dataset though:

Copied

```
my_dataset[0]  # fast
my_dataset = my_dataset.shuffle(seed=42)
my_dataset[0]  # up to 10x slower
my_dataset = my_dataset.flatten_indices()  # rewrite the shuffled dataset on disk as contiguous chunks of data
my_dataset[0]  # fast again
```

In this case, we recommend switching to an [IterableDataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset) and leveraging its fast approximate shuffling method [IterableDataset.shuffle()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset.shuffle).

It only shuffles the shards order and adds a shuffle buffer to your dataset, which keeps the speed of your dataset optimal:

Copied

```
my_iterable_dataset = my_dataset.to_iterable_dataset(num_shards=128)
for example in enumerate(my_iterable_dataset):  # fast
    pass

shuffled_iterable_dataset = my_iterable_dataset.shuffle(seed=42, buffer_size=100)

for example in enumerate(shuffled_iterable_dataset):  # as fast as before
    pass
```

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

# set a seed
>>> shuffled_ds = ds.shuffle(seed=42)
>>> shuffled_ds['label'][:10]
[1, 0, 1, 1, 0, 0, 0, 0, 0, 0]
```

**train\_test\_split**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L4258)

( test\_size: typing.Union\[float, int, NoneType] = Nonetrain\_size: typing.Union\[float, int, NoneType] = Noneshuffle: bool = Truestratify\_by\_column: typing.Optional\[str] = Noneseed: typing.Optional\[int] = Nonegenerator: typing.Optional\[numpy.random.\_generator.Generator] = Nonekeep\_in\_memory: bool = Falseload\_from\_cache\_file: typing.Optional\[bool] = Nonetrain\_indices\_cache\_file\_name: typing.Optional\[str] = Nonetest\_indices\_cache\_file\_name: typing.Optional\[str] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000train\_new\_fingerprint: typing.Optional\[str] = Nonetest\_new\_fingerprint: typing.Optional\[str] = None )

Parameters

* **test\_size** (`numpy.random.Generator`, *optional*) — Size of the test split If `float`, should be between `0.0` and `1.0` and represent the proportion of the dataset to include in the test split. If `int`, represents the absolute number of test samples. If `None`, the value is set to the complement of the train size. If `train_size` is also `None`, it will be set to `0.25`.
* **train\_size** (`numpy.random.Generator`, *optional*) — Size of the train split If `float`, should be between `0.0` and `1.0` and represent the proportion of the dataset to include in the train split. If `int`, represents the absolute number of train samples. If `None`, the value is automatically set to the complement of the test size.
* **shuffle** (`bool`, *optional*, defaults to `True`) — Whether or not to shuffle the data before splitting.
* **stratify\_by\_column** (`str`, *optional*, defaults to `None`) — The column name of labels to be used to perform stratified split of data.
* **seed** (`int`, *optional*) — A seed to initialize the default BitGenerator if `generator=None`. If `None`, then fresh, unpredictable entropy will be pulled from the OS. If an `int` or `array_like[ints]` is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state.
* **generator** (`numpy.random.Generator`, *optional*) — Numpy random Generator to use to compute the permutation of the dataset rows. If `generator=None` (default), uses `np.random.default_rng` (the default BitGenerator (PCG64) of NumPy).
* **keep\_in\_memory** (`bool`, defaults to `False`) — Keep the splits indices in memory instead of writing it to a cache file.
* **load\_from\_cache\_file** (`Optional[bool]`, defaults to `True` if caching is enabled) — If a cache file storing the splits indices can be identified, use it instead of recomputing.
* **train\_cache\_file\_name** (`str`, *optional*) — Provide the name of a path for the cache file. It is used to store the train split indices instead of the automatically generated cache file name.
* **test\_cache\_file\_name** (`str`, *optional*) — Provide the name of a path for the cache file. It is used to store the test split indices instead of the automatically generated cache file name.
* **writer\_batch\_size** (`int`, defaults to `1000`) — Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`.
* **train\_new\_fingerprint** (`str`, *optional*, defaults to `None`) — The new fingerprint of the train set after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments
* **test\_new\_fingerprint** (`str`, *optional*, defaults to `None`) — The new fingerprint of the test set after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments

Return a dictionary ([datasets.DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict)) with two random train and test subsets (`train` and `test` `Dataset` splits). Splits are created from the dataset according to `test_size`, `train_size` and `shuffle`.

This method is similar to scikit-learn `train_test_split`.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds = ds.train_test_split(test_size=0.2, shuffle=True)
DatasetDict({
    train: Dataset({
        features: ['text', 'label'],
        num_rows: 852
    })
    test: Dataset({
        features: ['text', 'label'],
        num_rows: 214
    })
})

# set a seed
>>> ds = ds.train_test_split(test_size=0.2, seed=42)

# stratified split
>>> ds = load_dataset("imdb",split="train")
Dataset({
    features: ['text', 'label'],
    num_rows: 25000
})
>>> ds = ds.train_test_split(test_size=0.2, stratify_by_column="label")
DatasetDict({
    train: Dataset({
        features: ['text', 'label'],
        num_rows: 20000
    })
    test: Dataset({
        features: ['text', 'label'],
        num_rows: 5000
    })
})
```

**shard**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L4541)

( num\_shards: intindex: intcontiguous: bool = Falsekeep\_in\_memory: bool = Falseindices\_cache\_file\_name: typing.Optional\[str] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000 )

Parameters

* **num\_shards** (`int`) — How many shards to split the dataset into.
* **index** (`int`) — Which shard to select and return. contiguous — (`bool`, defaults to `False`): Whether to select contiguous blocks of indices for shards.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Keep the dataset in memory instead of writing it to a cache file.
* **indices\_cache\_file\_name** (`str`, *optional*) — Provide the name of a path for the cache file. It is used to store the indices of each shard instead of the automatically generated cache file name.
* **writer\_batch\_size** (`int`, defaults to `1000`) — Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`.

Return the `index`-nth shard from dataset split into `num_shards` pieces.

This shards deterministically. `dset.shard(n, i)` will contain all elements of dset whose index mod `n = i`.

`dset.shard(n, i, contiguous=True)` will instead split dset into contiguous chunks, so it can be easily concatenated back together after processing. If `n % i == l`, then the first `l` shards will have length `(n // i) + 1`, and the remaining shards will have length `(n // i)`. `datasets.concatenate([dset.shard(n, i, contiguous=True) for i in range(n)])` will return a dataset with the same order as the original.

Be sure to shard before using any randomizing operator (such as `shuffle`). It is best if the shard operator is used early in the dataset pipeline.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="validation")
>>> ds
Dataset({
    features: ['text', 'label'],
    num_rows: 1066
})
>>> ds.shard(num_shards=2, index=0)
Dataset({
    features: ['text', 'label'],
    num_rows: 533
})
```

**to\_tf\_dataset**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L326)

( batch\_size: typing.Optional\[int] = Nonecolumns: typing.Union\[str, typing.List\[str], NoneType] = Noneshuffle: bool = Falsecollate\_fn: typing.Optional\[typing.Callable] = Nonedrop\_remainder: bool = Falsecollate\_fn\_args: typing.Union\[typing.Dict\[str, typing.Any], NoneType] = Nonelabel\_cols: typing.Union\[str, typing.List\[str], NoneType] = Noneprefetch: bool = Truenum\_workers: int = 0num\_test\_batches: int = 20 )

Parameters

* **batch\_size** (`int`, *optional*) — Size of batches to load from the dataset. Defaults to `None`, which implies that the dataset won’t be batched, but the returned dataset can be batched later with `tf_dataset.batch(batch_size)`.
* **columns** (`List[str]` or `str`, *optional*) — Dataset column(s) to load in the `tf.data.Dataset`. Column names that are created by the `collate_fn` and that do not exist in the original dataset can be used.
* **shuffle(`bool`,** defaults to `False`) — Shuffle the dataset order when loading. Recommended `True` for training, `False` for validation/evaluation.
* **drop\_remainder(`bool`,** defaults to `False`) — Drop the last incomplete batch when loading. Ensures that all batches yielded by the dataset will have the same length on the batch dimension.
* **collate\_fn(`Callable`,** *optional*) — A function or callable object (such as a `DataCollator`) that will collate lists of samples into a batch.
* **collate\_fn\_args** (`Dict`, *optional*) — An optional `dict` of keyword arguments to be passed to the `collate_fn`.
* **label\_cols** (`List[str]` or `str`, defaults to `None`) — Dataset column(s) to load as labels. Note that many models compute loss internally rather than letting Keras do it, in which case passing the labels here is optional, as long as they’re in the input `columns`.
* **prefetch** (`bool`, defaults to `True`) — Whether to run the dataloader in a separate thread and maintain a small buffer of batches for training. Improves performance by allowing data to be loaded in the background while the model is training.
* **num\_workers** (`int`, defaults to `0`) — Number of workers to use for loading the dataset. Only supported on Python versions >= 3.8.
* **num\_test\_batches** (`int`, defaults to `20`) — Number of batches to use to infer the output signature of the dataset. The higher this number, the more accurate the signature will be, but the longer it will take to create the dataset.

Create a `tf.data.Dataset` from the underlying Dataset. This `tf.data.Dataset` will load and collate batches from the Dataset, and is suitable for passing to methods like `model.fit()` or `model.predict()`. The dataset will yield `dicts` for both inputs and labels unless the `dict` would contain only a single key, in which case a raw `tf.Tensor` is yielded instead.

Example:

Copied

```
>>> ds_train = ds["train"].to_tf_dataset(
...    columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'],
...    shuffle=True,
...    batch_size=16,
...    collate_fn=data_collator,
... )
```

**push\_to\_hub**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L5354)

( repo\_id: strconfig\_name: str = 'default'split: typing.Optional\[str] = Noneprivate: typing.Optional\[bool] = Falsetoken: typing.Optional\[str] = Nonebranch: typing.Optional\[str] = Nonemax\_shard\_size: typing.Union\[str, int, NoneType] = Nonenum\_shards: typing.Optional\[int] = Noneembed\_external\_files: bool = True )

Parameters

* **repo\_id** (`str`) — The ID of the repository to push to in the following format: `<user>/<dataset_name>` or `<org>/<dataset_name>`. Also accepts `<dataset_name>`, which will default to the namespace of the logged-in user.
* **config\_name** (`str`, defaults to “default”) — The configuration name of a dataset. Defaults to “default”
* **split** (`str`, *optional*) — The name of the split that will be given to that dataset. Defaults to `self.split`.
* **private** (`bool`, *optional*, defaults to `False`) — Whether the dataset repository should be set to private or not. Only affects repository creation: a repository that already exists will not be affected by that parameter.
* **token** (`str`, *optional*) — An optional authentication token for the BOINC AI Hub. If no token is passed, will default to the token saved locally when logging in with `boincai-cli login`. Will raise an error if no token is passed and the user is not logged-in.
* **branch** (`str`, *optional*) — The git branch on which to push the dataset. This defaults to the default branch as specified in your repository, which defaults to `"main"`.
* **max\_shard\_size** (`int` or `str`, *optional*, defaults to `"500MB"`) — The maximum size of the dataset shards to be uploaded to the hub. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).
* **num\_shards** (`int`, *optional*) — Number of shards to write. By default the number of shards depends on `max_shard_size`.

  Added in 2.8.0
* **embed\_external\_files** (`bool`, defaults to `True`) — Whether to embed file bytes in the shards. In particular, this will do the following before the push for the fields of type:
  * [Audio](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Audio) and [Image](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Image): remove local path information and embed file content in the Parquet files.

Pushes the dataset to the hub as a Parquet dataset. The dataset is pushed using HTTP requests and does not need to have neither git or git-lfs installed.

The resulting Parquet files are self-contained by default. If your dataset contains [Image](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Image) or [Audio](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Audio) data, the Parquet files will store the bytes of your images or audio files. You can disable this by setting `embed_external_files` to `False`.

Example:

Copied

```
>>> dataset.push_to_hub("<organization>/<dataset_id>")
>>> dataset.push_to_hub("<organization>/<dataset_id>", split="validation")
>>> dataset.push_to_hub("<organization>/<dataset_id>", max_shard_size="1GB")
>>> dataset.push_to_hub("<organization>/<dataset_id>", num_shards=1024)
```

**save\_to\_disk**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1376)

( dataset\_path: typing.Union\[str, bytes, os.PathLike]fs = 'deprecated'max\_shard\_size: typing.Union\[str, int, NoneType] = Nonenum\_shards: typing.Optional\[int] = Nonenum\_proc: typing.Optional\[int] = Nonestorage\_options: typing.Optional\[dict] = None )

Parameters

* **dataset\_path** (`str`) — Path (e.g. `dataset/train`) or remote URI (e.g. `s3://my-bucket/dataset/train`) of the dataset directory where the dataset will be saved to.
* **fs** (`fsspec.spec.AbstractFileSystem`, *optional*) — Instance of the remote filesystem where the dataset will be saved to.

  Deprecated in 2.8.0

  `fs` was deprecated in version 2.8.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options`
* **max\_shard\_size** (`int` or `str`, *optional*, defaults to `"500MB"`) — The maximum size of the dataset shards to be uploaded to the hub. If expressed as a string, needs to be digits followed by a unit (like `"50MB"`).
* **num\_shards** (`int`, *optional*) — Number of shards to write. By default the number of shards depends on `max_shard_size` and `num_proc`.

  Added in 2.8.0
* **num\_proc** (`int`, *optional*) — Number of processes when downloading and generating the dataset locally. Multiprocessing is disabled by default.

  Added in 2.8.0
* **storage\_options** (`dict`, *optional*) — Key/value pairs to be passed on to the file-system backend, if any.

  Added in 2.8.0

Saves a dataset to a dataset directory, or in a filesystem using any implementation of `fsspec.spec.AbstractFileSystem`.

For [Image](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Image) and [Audio](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Audio) data:

All the Image() and Audio() data are stored in the arrow files. If you want to store paths or urls, please use the Value(“string”) type.

Example:

Copied

```
>>> ds.save_to_disk("path/to/dataset/directory")
>>> ds.save_to_disk("path/to/dataset/directory", max_shard_size="1GB")
>>> ds.save_to_disk("path/to/dataset/directory", num_shards=1024)
```

**load\_from\_disk**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1594)

( dataset\_path: strfs = 'deprecated'keep\_in\_memory: typing.Optional\[bool] = Nonestorage\_options: typing.Optional\[dict] = None ) → [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) or [DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict)

Parameters

* **dataset\_path** (`str`) — Path (e.g. `"dataset/train"`) or remote URI (e.g. `"s3//my-bucket/dataset/train"`) of the dataset directory where the dataset will be loaded from.
* **fs** (`fsspec.spec.AbstractFileSystem`, *optional*) — Instance of the remote filesystem where the dataset will be saved to.

  Deprecated in 2.8.0

  `fs` was deprecated in version 2.8.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options`
* **keep\_in\_memory** (`bool`, defaults to `None`) — Whether to copy the dataset in-memory. If `None`, the dataset will not be copied in-memory unless explicitly enabled by setting `datasets.config.IN_MEMORY_MAX_SIZE` to nonzero. See more details in the [improve performance](https://huggingface.co/docs/datasets/cache#improve-performance) section.
* **storage\_options** (`dict`, *optional*) — Key/value pairs to be passed on to the file-system backend, if any.

  Added in 2.8.0

Returns

[Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) or [DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict)

* If `dataset_path` is a path of a dataset directory, the dataset requested.
* If `dataset_path` is a path of a dataset dict directory, a `datasets.DatasetDict` with each split.

Loads a dataset that was previously saved using `save_to_disk` from a dataset directory, or from a filesystem using any implementation of `fsspec.spec.AbstractFileSystem`.

Example:

Copied

```
>>> ds = load_from_disk("path/to/dataset/directory")
```

**flatten\_indices**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L3652)

( keep\_in\_memory: bool = Falsecache\_file\_name: typing.Optional\[str] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000features: typing.Optional\[datasets.features.features.Features] = Nonedisable\_nullable: bool = Falsenum\_proc: typing.Optional\[int] = Nonenew\_fingerprint: typing.Optional\[str] = None )

Parameters

* **keep\_in\_memory** (`bool`, defaults to `False`) — Keep the dataset in memory instead of writing it to a cache file.
* **cache\_file\_name** (`str`, *optional*, default `None`) — Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name.
* **writer\_batch\_size** (`int`, defaults to `1000`) — Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`.
* **features** (`Optional[datasets.Features]`, defaults to `None`) — Use a specific [Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features) to store the cache file instead of the automatically generated one.
* **disable\_nullable** (`bool`, defaults to `False`) — Allow null values in the table.
* **num\_proc** (`int`, optional, default `None`) — Max number of processes when generating cache. Already cached shards are loaded sequentially
* **new\_fingerprint** (`str`, *optional*, defaults to `None`) — The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments

Create and cache a new Dataset by flattening the indices mapping.

**to\_csv**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L4707)

( path\_or\_buf: typing.Union\[str, bytes, os.PathLike, typing.BinaryIO]batch\_size: typing.Optional\[int] = Nonenum\_proc: typing.Optional\[int] = None\*\*to\_csv\_kwargs ) → `int`

Parameters

* **path\_or\_buf** (`PathLike` or `FileOrBuffer`) — Either a path to a file or a BinaryIO.
* **batch\_size** (`int`, *optional*) — Size of the batch to load in memory and write at once. Defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE`.
* **num\_proc** (`int`, *optional*) — Number of processes for multiprocessing. By default it doesn’t use multiprocessing. `batch_size` in this case defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE` but feel free to make it 5x or 10x of the default value if you have sufficient compute power.
* \***\*to\_csv\_kwargs** (additional keyword arguments) — Parameters to pass to pandas’s [`pandas.DataFrame.to_csv`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html).

  Changed in 2.10.0

  Now, `index` defaults to `False` if not specified.

  If you would like to write the index, pass `index=True` and also set a name for the index column by passing `index_label`.

Returns

`int`

The number of characters or bytes written.

Exports the dataset to csv

Example:

Copied

```
>>> ds.to_csv("path/to/dataset/directory")
```

**to\_pandas**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L4867)

( batch\_size: typing.Optional\[int] = Nonebatched: bool = False )

Parameters

* **batched** (`bool`) — Set to `True` to return a generator that yields the dataset as batches of `batch_size` rows. Defaults to `False` (returns the whole datasets once).
* **batch\_size** (`int`, *optional*) — The size (number of rows) of the batches if `batched` is `True`. Defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE`.

Returns the dataset as a `pandas.DataFrame`. Can also return a generator for large datasets.

Example:

Copied

```
>>> ds.to_pandas()
```

**to\_dict**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L4753)

( batch\_size: typing.Optional\[int] = Nonebatched = 'deprecated' )

Parameters

* **batched** (`bool`) — Set to `True` to return a generator that yields the dataset as batches of `batch_size` rows. Defaults to `False` (returns the whole datasets once).

  Deprecated in 2.11.0

  Use `.iter(batch_size=batch_size)` followed by `.to_dict()` on the individual batches instead.
* **batch\_size** (`int`, *optional*) — The size (number of rows) of the batches if `batched` is `True`. Defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE`.

Returns the dataset as a Python dict. Can also return a generator for large datasets.

Example:

Copied

```
>>> ds.to_dict()
```

**to\_json**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L4822)

( path\_or\_buf: typing.Union\[str, bytes, os.PathLike, typing.BinaryIO]batch\_size: typing.Optional\[int] = Nonenum\_proc: typing.Optional\[int] = None\*\*to\_json\_kwargs ) → `int`

Parameters

* **path\_or\_buf** (`PathLike` or `FileOrBuffer`) — Either a path to a file or a BinaryIO.
* **batch\_size** (`int`, *optional*) — Size of the batch to load in memory and write at once. Defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE`.
* **num\_proc** (`int`, *optional*) — Number of processes for multiprocessing. By default it doesn’t use multiprocessing. `batch_size` in this case defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE` but feel free to make it 5x or 10x of the default value if you have sufficient compute power.
* \***\*to\_json\_kwargs** (additional keyword arguments) — Parameters to pass to pandas’s [`pandas.DataFrame.to_json`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html).

  Changed in 2.11.0

  Now, `index` defaults to `False` if `orient` is `"split"` or `"table"`.

  If you would like to write the index, pass `index=True`.

Returns

`int`

The number of characters or bytes written.

Export the dataset to JSON Lines or JSON.

Example:

Copied

```
>>> ds.to_json("path/to/dataset/directory")
```

**to\_parquet**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L4906)

( path\_or\_buf: typing.Union\[str, bytes, os.PathLike, typing.BinaryIO]batch\_size: typing.Optional\[int] = None\*\*parquet\_writer\_kwargs ) → `int`

Parameters

* **path\_or\_buf** (`PathLike` or `FileOrBuffer`) — Either a path to a file or a BinaryIO.
* **batch\_size** (`int`, *optional*) — Size of the batch to load in memory and write at once. Defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE`.
* \***\*parquet\_writer\_kwargs** (additional keyword arguments) — Parameters to pass to PyArrow’s `pyarrow.parquet.ParquetWriter`.

Returns

`int`

The number of characters or bytes written.

Exports the dataset to parquet

Example:

Copied

```
>>> ds.to_parquet("path/to/dataset/directory")
```

**to\_sql**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L4937)

( name: strcon: typing.Union\[str, ForwardRef('sqlalchemy.engine.Connection'), ForwardRef('sqlalchemy.engine.Engine'), ForwardRef('sqlite3.Connection')]batch\_size: typing.Optional\[int] = None\*\*sql\_writer\_kwargs ) → `int`

Parameters

* **name** (`str`) — Name of SQL table.
* **con** (`str` or `sqlite3.Connection` or `sqlalchemy.engine.Connection` or `sqlalchemy.engine.Connection`) — A [URI string](https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls) or a SQLite3/SQLAlchemy connection object used to write to a database.
* **batch\_size** (`int`, *optional*) — Size of the batch to load in memory and write at once. Defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE`.
* \***\*sql\_writer\_kwargs** (additional keyword arguments) — Parameters to pass to pandas’s [`pandas.DataFrame.to_sql`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_sql.html).

  Changed in 2.11.0

  Now, `index` defaults to `False` if not specified.

  If you would like to write the index, pass `index=True` and also set a name for the index column by passing `index_label`.

Returns

`int`

The number of records written.

Exports the dataset to a SQL database.

Example:

Copied

```
>>> # con provided as a connection URI string
>>> ds.to_sql("data", "sqlite:///my_own_db.sql")
>>> # con provided as a sqlite3 connection object
>>> import sqlite3
>>> con = sqlite3.connect("my_own_db.sql")
>>> with con:
...     ds.to_sql("data", con)
```

**to\_iterable\_dataset**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L5029)

( num\_shards: typing.Optional\[int] = 1 )

Parameters

* **num\_shards** (`int`, default to `1`) — Number of shards to define when instantiating the iterable dataset. This is especially useful for big datasets to be able to shuffle properly, and also to enable fast parallel loading using a PyTorch DataLoader or in distributed setups for example. Shards are defined using [datasets.Dataset.shard()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.shard): it simply slices the data without writing anything on disk.

Get an [datasets.IterableDataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset) from a map-style [datasets.Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset). This is equivalent to loading a dataset in streaming mode with [datasets.load\_dataset()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/loading_methods#datasets.load_dataset), but much faster since the data is streamed from local files.

Contrary to map-style datasets, iterable datasets are lazy and can only be iterated over (e.g. using a for loop). Since they are read sequentially in training loops, iterable datasets are much faster than map-style datasets. All the transformations applied to iterable datasets like filtering or processing are done on-the-fly when you start iterating over the dataset.

Still, it is possible to shuffle an iterable dataset using [datasets.IterableDataset.shuffle()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset.shuffle). This is a fast approximate shuffling that works best if you have multiple shards and if you specify a buffer size that is big enough.

To get the best speed performance, make sure your dataset doesn’t have an indices mapping. If this is the case, the data are not read contiguously, which can be slow sometimes. You can use `ds = ds.flatten_indices()` to write your dataset in contiguous chunks of data and have optimal speed before switching to an iterable dataset.

Example:

Basic usage:

Copied

```
>>> ids = ds.to_iterable_dataset()
>>> for example in ids:
...     pass
```

With lazy filtering and processing:

Copied

```
>>> ids = ds.to_iterable_dataset()
>>> ids = ids.filter(filter_fn).map(process_fn)  # will filter and process on-the-fly when you start iterating over the iterable dataset
>>> for example in ids:
...     pass
```

With sharding to enable efficient shuffling:

Copied

```
>>> ids = ds.to_iterable_dataset(num_shards=64)  # the dataset is split into 64 shards to be iterated over
>>> ids = ids.shuffle(buffer_size=10_000)  # will shuffle the shards order and use a shuffle buffer for fast approximate shuffling when you start iterating
>>> for example in ids:
...     pass
```

With a PyTorch DataLoader:

Copied

```
>>> import torch
>>> ids = ds.to_iterable_dataset(num_shards=64)
>>> ids = ids.filter(filter_fn).map(process_fn)
>>> dataloader = torch.utils.data.DataLoader(ids, num_workers=4)  # will assign 64 / 4 = 16 shards to each worker to load, filter and process when you start iterating
>>> for example in ids:
...     pass
```

With a PyTorch DataLoader and shuffling:

Copied

```
>>> import torch
>>> ids = ds.to_iterable_dataset(num_shards=64)
>>> ids = ids.shuffle(buffer_size=10_000)  # will shuffle the shards order and use a shuffle buffer when you start iterating
>>> dataloader = torch.utils.data.DataLoader(ids, num_workers=4)  # will assign 64 / 4 = 16 shards from the shuffled list of shards to each worker when you start iterating
>>> for example in ids:
...     pass
```

In a distributed setup like PyTorch DDP with a PyTorch DataLoader and shuffling

Copied

```
>>> from datasets.distributed import split_dataset_by_node
>>> ids = ds.to_iterable_dataset(num_shards=512)
>>> ids = ids.shuffle(buffer_size=10_000)  # will shuffle the shards order and use a shuffle buffer when you start iterating
>>> ids = split_dataset_by_node(ds, world_size=8, rank=0)  # will keep only 512 / 8 = 64 shards from the shuffled lists of shards when you start iterating
>>> dataloader = torch.utils.data.DataLoader(ids, num_workers=4)  # will assign 64 / 4 = 16 shards from this node's list of shards to each worker when you start iterating
>>> for example in ids:
...     pass
```

With shuffling and multiple epochs:

Copied

```
>>> ids = ds.to_iterable_dataset(num_shards=64)
>>> ids = ids.shuffle(buffer_size=10_000, seed=42)  # will shuffle the shards order and use a shuffle buffer when you start iterating
>>> for epoch in range(n_epochs):
...     ids.set_epoch(epoch)  # will use effective_seed = seed + epoch to shuffle the shards and for the shuffle buffer when you start iterating
...     for example in ids:
...         pass
```

Feel free to also use \`IterableDataset.set\_epoch()\` when using a PyTorch DataLoader or in distributed setups.

**add\_faiss\_index**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L5628)

( column: strindex\_name: typing.Optional\[str] = Nonedevice: typing.Optional\[int] = Nonestring\_factory: typing.Optional\[str] = Nonemetric\_type: typing.Optional\[int] = Nonecustom\_index: typing.Optional\[ForwardRef('faiss.Index')] = Nonebatch\_size: int = 1000train\_size: typing.Optional\[int] = Nonefaiss\_verbose: bool = Falsedtype = \<class 'numpy.float32'> )

Parameters

* **column** (`str`) — The column of the vectors to add to the index.
* **index\_name** (`str`, *optional*) — The `index_name`/identifier of the index. This is the `index_name` that is used to call [get\_nearest\_examples()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.get_nearest_examples) or [search()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.search). By default it corresponds to `column`.
* **device** (`Union[int, List[int]]`, *optional*) — If positive integer, this is the index of the GPU to use. If negative integer, use all GPUs. If a list of positive integers is passed in, run only on those GPUs. By default it uses the CPU.
* **string\_factory** (`str`, *optional*) — This is passed to the index factory of Faiss to create the index. Default index class is `IndexFlat`.
* **metric\_type** (`int`, *optional*) — Type of metric. Ex: `faiss.METRIC_INNER_PRODUCT` or `faiss.METRIC_L2`.
* **custom\_index** (`faiss.Index`, *optional*) — Custom Faiss index that you already have instantiated and configured for your needs.
* **batch\_size** (`int`) — Size of the batch to use while adding vectors to the `FaissIndex`. Default value is `1000`.

  Added in 2.4.0
* **train\_size** (`int`, *optional*) — If the index needs a training step, specifies how many vectors will be used to train the index.
* **faiss\_verbose** (`bool`, defaults to `False`) — Enable the verbosity of the Faiss index.
* **dtype** (`data-type`) — The dtype of the numpy arrays that are indexed. Default is `np.float32`.

Add a dense index using Faiss for fast retrieval. By default the index is done over the vectors of the specified column. You can specify `device` if you want to run it on GPU (`device` must be the GPU index). You can find more information about Faiss here:

* For [string factory](https://github.com/facebookresearch/faiss/wiki/The-index-factory)

Example:

Copied

```
>>> ds = datasets.load_dataset('crime_and_punish', split='train')
>>> ds_with_embeddings = ds.map(lambda example: {'embeddings': embed(example['line']}))
>>> ds_with_embeddings.add_faiss_index(column='embeddings')
>>> # query
>>> scores, retrieved_examples = ds_with_embeddings.get_nearest_examples('embeddings', embed('my new query'), k=10)
>>> # save index
>>> ds_with_embeddings.save_faiss_index('embeddings', 'my_index.faiss')

>>> ds = datasets.load_dataset('crime_and_punish', split='train')
>>> # load index
>>> ds.load_faiss_index('embeddings', 'my_index.faiss')
>>> # query
>>> scores, retrieved_examples = ds.get_nearest_examples('embeddings', embed('my new query'), k=10)
```

**add\_faiss\_index\_from\_external\_arrays**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L5708)

( external\_arrays: arrayindex\_name: strdevice: typing.Optional\[int] = Nonestring\_factory: typing.Optional\[str] = Nonemetric\_type: typing.Optional\[int] = Nonecustom\_index: typing.Optional\[ForwardRef('faiss.Index')] = Nonebatch\_size: int = 1000train\_size: typing.Optional\[int] = Nonefaiss\_verbose: bool = Falsedtype = \<class 'numpy.float32'> )

Parameters

* **external\_arrays** (`np.array`) — If you want to use arrays from outside the lib for the index, you can set `external_arrays`. It will use `external_arrays` to create the Faiss index instead of the arrays in the given `column`.
* **index\_name** (`str`) — The `index_name`/identifier of the index. This is the `index_name` that is used to call [get\_nearest\_examples()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.get_nearest_examples) or [search()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.search).
* **device** (Optional `Union[int, List[int]]`, *optional*) — If positive integer, this is the index of the GPU to use. If negative integer, use all GPUs. If a list of positive integers is passed in, run only on those GPUs. By default it uses the CPU.
* **string\_factory** (`str`, *optional*) — This is passed to the index factory of Faiss to create the index. Default index class is `IndexFlat`.
* **metric\_type** (`int`, *optional*) — Type of metric. Ex: `faiss.faiss.METRIC_INNER_PRODUCT` or `faiss.METRIC_L2`.
* **custom\_index** (`faiss.Index`, *optional*) — Custom Faiss index that you already have instantiated and configured for your needs.
* **batch\_size** (`int`, *optional*) — Size of the batch to use while adding vectors to the FaissIndex. Default value is 1000.

  Added in 2.4.0
* **train\_size** (`int`, *optional*) — If the index needs a training step, specifies how many vectors will be used to train the index.
* **faiss\_verbose** (`bool`, defaults to False) — Enable the verbosity of the Faiss index.
* **dtype** (`numpy.dtype`) — The dtype of the numpy arrays that are indexed. Default is np.float32.

Add a dense index using Faiss for fast retrieval. The index is created using the vectors of `external_arrays`. You can specify `device` if you want to run it on GPU (`device` must be the GPU index). You can find more information about Faiss here:

* For [string factory](https://github.com/facebookresearch/faiss/wiki/The-index-factory)

**save\_faiss\_index**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/search.py#L528)

( index\_name: strfile: typing.Union\[str, pathlib.PurePath]storage\_options: typing.Optional\[typing.Dict] = None )

Parameters

* **index\_name** (`str`) — The index\_name/identifier of the index. This is the index\_name that is used to call `.get_nearest` or `.search`.
* **file** (`str`) — The path to the serialized faiss index on disk or remote URI (e.g. `"s3://my-bucket/index.faiss"`).
* **storage\_options** (`dict`, *optional*) — Key/value pairs to be passed on to the file-system backend, if any.

  Added in 2.11.0

Save a FaissIndex on disk.

**load\_faiss\_index**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/search.py#L546)

( index\_name: strfile: typing.Union\[str, pathlib.PurePath]device: typing.Union\[int, typing.List\[int], NoneType] = Nonestorage\_options: typing.Optional\[typing.Dict] = None )

Parameters

* **index\_name** (`str`) — The index\_name/identifier of the index. This is the index\_name that is used to call `.get_nearest` or `.search`.
* **file** (`str`) — The path to the serialized faiss index on disk or remote URI (e.g. `"s3://my-bucket/index.faiss"`).
* **device** (Optional `Union[int, List[int]]`) — If positive integer, this is the index of the GPU to use. If negative integer, use all GPUs. If a list of positive integers is passed in, run only on those GPUs. By default it uses the CPU.
* **storage\_options** (`dict`, *optional*) — Key/value pairs to be passed on to the file-system backend, if any.

  Added in 2.11.0

Load a FaissIndex from disk.

If you want to do additional configurations, you can have access to the faiss index object by doing `.get_index(index_name).faiss_index` to make it fit your needs.

**add\_elasticsearch\_index**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L5767)

( column: strindex\_name: typing.Optional\[str] = Nonehost: typing.Optional\[str] = Noneport: typing.Optional\[int] = Nonees\_client: typing.Optional\[ForwardRef('elasticsearch.Elasticsearch')] = Nonees\_index\_name: typing.Optional\[str] = Nonees\_index\_config: typing.Optional\[dict] = None )

Parameters

* **column** (`str`) — The column of the documents to add to the index.
* **index\_name** (`str`, *optional*) — The `index_name`/identifier of the index. This is the index name that is used to call [get\_nearest\_examples()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.get_nearest_examples) or [Dataset.search()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.search). By default it corresponds to `column`.
* **host** (`str`, *optional*, defaults to `localhost`) — Host of where ElasticSearch is running.
* **port** (`str`, *optional*, defaults to `9200`) — Port of where ElasticSearch is running.
* **es\_client** (`elasticsearch.Elasticsearch`, *optional*) — The elasticsearch client used to create the index if host and port are `None`.
* **es\_index\_name** (`str`, *optional*) — The elasticsearch index name used to create the index.
* **es\_index\_config** (`dict`, *optional*) — The configuration of the elasticsearch index. Default config is:

Add a text index using ElasticSearch for fast retrieval. This is done in-place.

Example:

Copied

```
>>> es_client = elasticsearch.Elasticsearch()
>>> ds = datasets.load_dataset('crime_and_punish', split='train')
>>> ds.add_elasticsearch_index(column='line', es_client=es_client, es_index_name="my_es_index")
>>> scores, retrieved_examples = ds.get_nearest_examples('line', 'my new query', k=10)
```

**load\_elasticsearch\_index**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/search.py#L630)

( index\_name: stres\_index\_name: strhost: typing.Optional\[str] = Noneport: typing.Optional\[int] = Nonees\_client: typing.Optional\[ForwardRef('Elasticsearch')] = Nonees\_index\_config: typing.Optional\[dict] = None )

Parameters

* **index\_name** (`str`) — The `index_name`/identifier of the index. This is the index name that is used to call `get_nearest` or `search`.
* **es\_index\_name** (`str`) — The name of elasticsearch index to load.
* **host** (`str`, *optional*, defaults to `localhost`) — Host of where ElasticSearch is running.
* **port** (`str`, *optional*, defaults to `9200`) — Port of where ElasticSearch is running.
* **es\_client** (`elasticsearch.Elasticsearch`, *optional*) — The elasticsearch client used to create the index if host and port are `None`.
* **es\_index\_config** (`dict`, *optional*) — The configuration of the elasticsearch index. Default config is:

Load an existing text index using ElasticSearch for fast retrieval.

**list\_indexes**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/search.py#L431)

( )

List the `colindex_nameumns`/identifiers of all the attached indexes.

**get\_index**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/search.py#L435)

( index\_name: str )

Parameters

* **index\_name** (`str`) — Index name.

List the `index_name`/identifiers of all the attached indexes.

**drop\_index**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/search.py#L677)

( index\_name: str )

Parameters

* **index\_name** (`str`) — The `index_name`/identifier of the index.

Drop the index with the specified column.

**search**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/search.py#L686)

( index\_name: strquery: typing.Union\[str, \<built-in function array>]k: int = 10\*\*kwargs ) → `(scores, indices)`

Parameters

* **index\_name** (`str`) — The name/identifier of the index.
* **query** (`Union[str, np.ndarray]`) — The query as a string if `index_name` is a text index or as a numpy array if `index_name` is a vector index.
* **k** (`int`) — The number of examples to retrieve.

Returns

`(scores, indices)`

A tuple of `(scores, indices)` where:

* **scores** (`List[List[float]`): the retrieval scores from either FAISS (`IndexFlatL2` by default) or ElasticSearch of the retrieved examples
* **indices** (`List[List[int]]`): the indices of the retrieved examples

Find the nearest examples indices in the dataset to the query.

**search\_batch**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/search.py#L706)

( index\_name: strqueries: typing.Union\[typing.List\[str], \<built-in function array>]k: int = 10\*\*kwargs ) → `(total_scores, total_indices)`

Parameters

* **index\_name** (`str`) — The `index_name`/identifier of the index.
* **queries** (`Union[List[str], np.ndarray]`) — The queries as a list of strings if `index_name` is a text index or as a numpy array if `index_name` is a vector index.
* **k** (`int`) — The number of examples to retrieve per query.

Returns

`(total_scores, total_indices)`

A tuple of `(total_scores, total_indices)` where:

* **total\_scores** (`List[List[float]`): the retrieval scores from either FAISS (`IndexFlatL2` by default) or ElasticSearch of the retrieved examples per query
* **total\_indices** (`List[List[int]]`): the indices of the retrieved examples per query

Find the nearest examples indices in the dataset to the query.

**get\_nearest\_examples**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/search.py#L728)

( index\_name: strquery: typing.Union\[str, \<built-in function array>]k: int = 10\*\*kwargs ) → `(scores, examples)`

Parameters

* **index\_name** (`str`) — The index\_name/identifier of the index.
* **query** (`Union[str, np.ndarray]`) — The query as a string if `index_name` is a text index or as a numpy array if `index_name` is a vector index.
* **k** (`int`) — The number of examples to retrieve.

Returns

`(scores, examples)`

A tuple of `(scores, examples)` where:

* **scores** (`List[float]`): the retrieval scores from either FAISS (`IndexFlatL2` by default) or ElasticSearch of the retrieved examples
* **examples** (`dict`): the retrieved examples

Find the nearest examples in the dataset to the query.

**get\_nearest\_examples\_batch**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/search.py#L752)

( index\_name: strqueries: typing.Union\[typing.List\[str], \<built-in function array>]k: int = 10\*\*kwargs ) → `(total_scores, total_examples)`

Parameters

* **index\_name** (`str`) — The `index_name`/identifier of the index.
* **queries** (`Union[List[str], np.ndarray]`) — The queries as a list of strings if `index_name` is a text index or as a numpy array if `index_name` is a vector index.
* **k** (`int`) — The number of examples to retrieve per query.

Returns

`(total_scores, total_examples)`

A tuple of `(total_scores, total_examples)` where:

* **total\_scores** (`List[List[float]`): the retrieval scores from either FAISS (`IndexFlatL2` by default) or ElasticSearch of the retrieved examples per query
* **total\_examples** (`List[dict]`): the retrieved examples per query

Find the nearest examples in the dataset to the query.

**info**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L158)

( )

[DatasetInfo](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetInfo) object containing all the metadata in the dataset.

**split**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L163)

( )

[NamedSplit](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.NamedSplit) object corresponding to a named dataset split.

**builder\_name**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L168)

( )

**citation**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L172)

( )

**config\_name**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L176)

( )

**dataset\_size**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L180)

( )

**description**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L184)

( )

**download\_checksums**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L188)

( )

**download\_size**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L192)

( )

**features**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L729)

( )

**homepage**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L200)

( )

**license**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L204)

( )

**size\_in\_bytes**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L208)

( )

**supervised\_keys**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L212)

( )

**version**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L220)

( )

**from\_csv**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L953)

( path\_or\_paths: typing.Union\[str, bytes, os.PathLike, typing.List\[typing.Union\[str, bytes, os.PathLike]]]split: typing.Optional\[datasets.splits.NamedSplit] = Nonefeatures: typing.Optional\[datasets.features.features.Features] = Nonecache\_dir: str = Nonekeep\_in\_memory: bool = Falsenum\_proc: typing.Optional\[int] = None\*\*kwargs )

Parameters

* **path\_or\_paths** (`path-like` or list of `path-like`) — Path(s) of the CSV file(s).
* **split** ([NamedSplit](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.NamedSplit), *optional*) — Split name to be assigned to the dataset.
* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features), *optional*) — Dataset features.
* **cache\_dir** (`str`, *optional*, defaults to `"~/.cache/boincai/datasets"`) — Directory to cache data.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.
* **num\_proc** (`int`, *optional*, defaults to `None`) — Number of processes when downloading and generating the dataset locally. This is helpful if the dataset is made of multiple files. Multiprocessing is disabled by default.

  Added in 2.8.0
* \***\*kwargs** (additional keyword arguments) — Keyword arguments to be passed to `pandas.read_csv`.

Create Dataset from CSV file(s).

Example:

Copied

```
>>> ds = Dataset.from_csv('path/to/dataset.csv')
```

**from\_json**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1074)

( path\_or\_paths: typing.Union\[str, bytes, os.PathLike, typing.List\[typing.Union\[str, bytes, os.PathLike]]]split: typing.Optional\[datasets.splits.NamedSplit] = Nonefeatures: typing.Optional\[datasets.features.features.Features] = Nonecache\_dir: str = Nonekeep\_in\_memory: bool = Falsefield: typing.Optional\[str] = Nonenum\_proc: typing.Optional\[int] = None\*\*kwargs )

Parameters

* **path\_or\_paths** (`path-like` or list of `path-like`) — Path(s) of the JSON or JSON Lines file(s).
* **split** ([NamedSplit](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.NamedSplit), *optional*) — Split name to be assigned to the dataset.
* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features), *optional*) — Dataset features.
* **cache\_dir** (`str`, *optional*, defaults to `"~/.cache/boincai/datasets"`) — Directory to cache data.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.
* **field** (`str`, *optional*) — Field name of the JSON file where the dataset is contained in.
* **num\_proc** (`int`, *optional* defaults to `None`) — Number of processes when downloading and generating the dataset locally. This is helpful if the dataset is made of multiple files. Multiprocessing is disabled by default.

  Added in 2.8.0
* \***\*kwargs** (additional keyword arguments) — Keyword arguments to be passed to `JsonConfig`.

Create Dataset from JSON or JSON Lines file(s).

Example:

Copied

```
>>> ds = Dataset.from_json('path/to/dataset.json')
```

**from\_parquet**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1131)

( path\_or\_paths: typing.Union\[str, bytes, os.PathLike, typing.List\[typing.Union\[str, bytes, os.PathLike]]]split: typing.Optional\[datasets.splits.NamedSplit] = Nonefeatures: typing.Optional\[datasets.features.features.Features] = Nonecache\_dir: str = Nonekeep\_in\_memory: bool = Falsecolumns: typing.Optional\[typing.List\[str]] = Nonenum\_proc: typing.Optional\[int] = None\*\*kwargs )

Parameters

* **path\_or\_paths** (`path-like` or list of `path-like`) — Path(s) of the Parquet file(s).
* **split** (`NamedSplit`, *optional*) — Split name to be assigned to the dataset.
* **features** (`Features`, *optional*) — Dataset features.
* **cache\_dir** (`str`, *optional*, defaults to `"~/.cache/boincai/datasets"`) — Directory to cache data.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.
* **columns** (`List[str]`, *optional*) — If not `None`, only these columns will be read from the file. A column name may be a prefix of a nested field, e.g. ‘a’ will select ‘a.b’, ‘a.c’, and ‘a.d.e’.
* **num\_proc** (`int`, *optional*, defaults to `None`) — Number of processes when downloading and generating the dataset locally. This is helpful if the dataset is made of multiple files. Multiprocessing is disabled by default.

  Added in 2.8.0
* \***\*kwargs** (additional keyword arguments) — Keyword arguments to be passed to `ParquetConfig`.

Create Dataset from Parquet file(s).

Example:

Copied

```
>>> ds = Dataset.from_parquet('path/to/dataset.parquet')
```

**from\_text**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1190)

( path\_or\_paths: typing.Union\[str, bytes, os.PathLike, typing.List\[typing.Union\[str, bytes, os.PathLike]]]split: typing.Optional\[datasets.splits.NamedSplit] = Nonefeatures: typing.Optional\[datasets.features.features.Features] = Nonecache\_dir: str = Nonekeep\_in\_memory: bool = Falsenum\_proc: typing.Optional\[int] = None\*\*kwargs )

Parameters

* **path\_or\_paths** (`path-like` or list of `path-like`) — Path(s) of the text file(s).
* **split** (`NamedSplit`, *optional*) — Split name to be assigned to the dataset.
* **features** (`Features`, *optional*) — Dataset features.
* **cache\_dir** (`str`, *optional*, defaults to `"~/.cache/boincai/datasets"`) — Directory to cache data.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.
* **num\_proc** (`int`, *optional*, defaults to `None`) — Number of processes when downloading and generating the dataset locally. This is helpful if the dataset is made of multiple files. Multiprocessing is disabled by default.

  Added in 2.8.0
* \***\*kwargs** (additional keyword arguments) — Keyword arguments to be passed to `TextConfig`.

Create Dataset from text file(s).

Example:

Copied

```
>>> ds = Dataset.from_text('path/to/dataset.txt')
```

**from\_sql**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L1305)

( sql: typing.Union\[str, ForwardRef('sqlalchemy.sql.Selectable')]con: typing.Union\[str, ForwardRef('sqlalchemy.engine.Connection'), ForwardRef('sqlalchemy.engine.Engine'), ForwardRef('sqlite3.Connection')]features: typing.Optional\[datasets.features.features.Features] = Nonecache\_dir: str = Nonekeep\_in\_memory: bool = False\*\*kwargs )

Parameters

* **sql** (`str` or `sqlalchemy.sql.Selectable`) — SQL query to be executed or a table name.
* **con** (`str` or `sqlite3.Connection` or `sqlalchemy.engine.Connection` or `sqlalchemy.engine.Connection`) — A [URI string](https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls) used to instantiate a database connection or a SQLite3/SQLAlchemy connection object.
* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features), *optional*) — Dataset features.
* **cache\_dir** (`str`, *optional*, defaults to `"~/.cache/boincai/datasets"`) — Directory to cache data.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.
* \***\*kwargs** (additional keyword arguments) — Keyword arguments to be passed to `SqlConfig`.

Create Dataset from SQL query or database table.

Example:

Copied

```
>>> # Fetch a database table
>>> ds = Dataset.from_sql("test_data", "postgres:///db_name")
>>> # Execute a SQL query on the table
>>> ds = Dataset.from_sql("SELECT sentence FROM test_data", "postgres:///db_name")
>>> # Use a Selectable object to specify the query
>>> from sqlalchemy import select, text
>>> stmt = select([text("sentence")]).select_from(text("test_data"))
>>> ds = Dataset.from_sql(stmt, "postgres:///db_name")
```

The returned dataset can only be cached if `con` is specified as URI string.

**prepare\_for\_task**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L2722)

( task: typing.Union\[str, datasets.tasks.base.TaskTemplate]id: int = 0 )

Parameters

* **task** (`Union[str, TaskTemplate]`) — The task to prepare the dataset for during training and evaluation. If `str`, supported tasks include:

  * `"text-classification"`
  * `"question-answering"`

  If `TaskTemplate`, must be one of the task templates in [`datasets.tasks`](https://huggingface.co/docs/datasets/package_reference/task_templates).
* **id** (`int`, defaults to `0`) — The id required to unambiguously identify the task template when multiple task templates of the same type are supported.

Prepare a dataset for the given task by casting the dataset’s [Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features) to standardized column names and types as detailed in [`datasets.tasks`](https://huggingface.co/docs/datasets/package_reference/task_templates).

Casts `datasets.DatasetInfo.features` according to a task-specific schema. Intended for single-use only, so all task templates are removed from `datasets.DatasetInfo.task_templates` after casting.

**align\_labels\_with\_mapping**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L5889)

( label2id: typing.Dictlabel\_column: str )

Parameters

* **label2id** (`dict`) — The label name to ID mapping to align the dataset with.
* **label\_column** (`str`) — The column name of labels to align on.

Align the dataset’s label ID and label name mapping to match an input `label2id` mapping. This is useful when you want to ensure that a model’s predicted labels are aligned with the dataset. The alignment in done using the lowercase label names.

Example:

Copied

```
>>> # dataset with mapping {'entailment': 0, 'neutral': 1, 'contradiction': 2}
>>> ds = load_dataset("glue", "mnli", split="train")
>>> # mapping to align with
>>> label2id = {'CONTRADICTION': 0, 'NEUTRAL': 1, 'ENTAILMENT': 2}
>>> ds_aligned = ds.align_labels_with_mapping(label2id, "label")
```

**datasets.concatenate\_datasets**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/combine.py#L158)

( dsets: typing.List\[\~DatasetType]info: typing.Optional\[datasets.info.DatasetInfo] = Nonesplit: typing.Optional\[datasets.splits.NamedSplit] = Noneaxis: int = 0 )

Parameters

* **dsets** (`List[datasets.Dataset]`) — List of Datasets to concatenate.
* **info** (`DatasetInfo`, *optional*) — Dataset information, like description, citation, etc.
* **split** (`NamedSplit`, *optional*) — Name of the dataset split.
* **axis** (`{0, 1}`, defaults to `0`) — Axis to concatenate over, where `0` means over rows (vertically) and `1` means over columns (horizontally).

  Added in 1.6.0

Converts a list of [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) with the same schema into a single [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset).

Example:

Copied

```
>>> ds3 = concatenate_datasets([ds1, ds2])
```

**datasets.interleave\_datasets**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/combine.py#L18)

( datasets: typing.List\[\~DatasetType]probabilities: typing.Optional\[typing.List\[float]] = Noneseed: typing.Optional\[int] = Noneinfo: typing.Optional\[datasets.info.DatasetInfo] = Nonesplit: typing.Optional\[datasets.splits.NamedSplit] = Nonestopping\_strategy: typing.Literal\['first\_exhausted', 'all\_exhausted'] = 'first\_exhausted' ) → [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) or [IterableDataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset)

Parameters

* **datasets** (`List[Dataset]` or `List[IterableDataset]`) — List of datasets to interleave.
* **probabilities** (`List[float]`, *optional*, defaults to `None`) — If specified, the new dataset is constructed by sampling examples from one source at a time according to these probabilities.
* **seed** (`int`, *optional*, defaults to `None`) — The random seed used to choose a source for each example.
* **info** ([DatasetInfo](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetInfo), *optional*) — Dataset information, like description, citation, etc.

  Added in 2.4.0
* **split** ([NamedSplit](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.NamedSplit), *optional*) — Name of the dataset split.

  Added in 2.4.0
* **stopping\_strategy** (`str`, defaults to `first_exhausted`) — Two strategies are proposed right now, `first_exhausted` and `all_exhausted`. By default, `first_exhausted` is an undersampling strategy, i.e the dataset construction is stopped as soon as one dataset has ran out of samples. If the strategy is `all_exhausted`, we use an oversampling strategy, i.e the dataset construction is stopped as soon as every samples of every dataset has been added at least once. Note that if the strategy is `all_exhausted`, the interleaved dataset size can get enormous:
  * with no probabilities, the resulting dataset will have `max_length_datasets*nb_dataset` samples.
  * with given probabilities, the resulting dataset will have more samples if some datasets have really low probability of visiting.

Returns

[Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) or [IterableDataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset)

Return type depends on the input `datasets` parameter. `Dataset` if the input is a list of `Dataset`, `IterableDataset` if the input is a list of `IterableDataset`.

Interleave several datasets (sources) into a single dataset. The new dataset is constructed by alternating between the sources to get the examples.

You can use this function on a list of [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) objects, or on a list of [IterableDataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset) objects.

* If `probabilities` is `None` (default) the new dataset is constructed by cycling between each source to get the examples.
* If `probabilities` is not `None`, the new dataset is constructed by getting examples from a random source at a time according to the provided probabilities.

The resulting dataset ends when one of the source datasets runs out of examples except when `oversampling` is `True`, in which case, the resulting dataset ends when all datasets have ran out of examples at least one time.

Note for iterable datasets:

In a distributed setup or in PyTorch DataLoader workers, the stopping strategy is applied per process. Therefore the “first\_exhausted” strategy on an sharded iterable dataset can generate less samples in total (up to 1 missing sample per subdataset per worker).

Example:

For regular datasets (map-style):

Copied

```
>>> from datasets import Dataset, interleave_datasets
>>> d1 = Dataset.from_dict({"a": [0, 1, 2]})
>>> d2 = Dataset.from_dict({"a": [10, 11, 12]})
>>> d3 = Dataset.from_dict({"a": [20, 21, 22]})
>>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42, stopping_strategy="all_exhausted")
>>> dataset["a"]
[10, 0, 11, 1, 2, 20, 12, 10, 0, 1, 2, 21, 0, 11, 1, 2, 0, 1, 12, 2, 10, 0, 22]
>>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42)
>>> dataset["a"]
[10, 0, 11, 1, 2]
>>> dataset = interleave_datasets([d1, d2, d3])
>>> dataset["a"]
[0, 10, 20, 1, 11, 21, 2, 12, 22]
>>> dataset = interleave_datasets([d1, d2, d3], stopping_strategy="all_exhausted")
>>> dataset["a"]
[0, 10, 20, 1, 11, 21, 2, 12, 22]
>>> d1 = Dataset.from_dict({"a": [0, 1, 2]})
>>> d2 = Dataset.from_dict({"a": [10, 11, 12, 13]})
>>> d3 = Dataset.from_dict({"a": [20, 21, 22, 23, 24]})
>>> dataset = interleave_datasets([d1, d2, d3])
>>> dataset["a"]
[0, 10, 20, 1, 11, 21, 2, 12, 22]
>>> dataset = interleave_datasets([d1, d2, d3], stopping_strategy="all_exhausted")
>>> dataset["a"]
[0, 10, 20, 1, 11, 21, 2, 12, 22, 0, 13, 23, 1, 10, 24]
>>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42)
>>> dataset["a"]
[10, 0, 11, 1, 2]
>>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42, stopping_strategy="all_exhausted")
>>> dataset["a"]
[10, 0, 11, 1, 2, 20, 12, 13, ..., 0, 1, 2, 0, 24]
For datasets in streaming mode (iterable):

>>> from datasets import load_dataset, interleave_datasets
>>> d1 = load_dataset("oscar", "unshuffled_deduplicated_en", split="train", streaming=True)
>>> d2 = load_dataset("oscar", "unshuffled_deduplicated_fr", split="train", streaming=True)
>>> dataset = interleave_datasets([d1, d2])
>>> iterator = iter(dataset)
>>> next(iterator)
{'text': 'Mtendere Village was inspired by the vision...}
>>> next(iterator)
{'text': "Média de débat d'idées, de culture...}
```

**datasets.distributed.split\_dataset\_by\_node**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/distributed.py#L10)

( dataset: DatasetTyperank: intworld\_size: int ) → [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) or [IterableDataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset)

Parameters

* **dataset** ([Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) or [IterableDataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset)) — The dataset to split by node.
* **rank** (`int`) — Rank of the current node.
* **world\_size** (`int`) — Total number of nodes.

Returns

[Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) or [IterableDataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset)

The dataset to be used on the node at rank `rank`.

Split a dataset for the node at rank `rank` in a pool of nodes of size `world_size`.

For map-style datasets:

Each node is assigned a chunk of data, e.g. rank 0 is given the first chunk of the dataset. To maximize data loading throughput, chunks are made of contiguous data on disk if possible.

For iterable datasets:

If the dataset has a number of shards that is a factor of `world_size` (i.e. if `dataset.n_shards % world_size == 0`), then the shards are evenly assigned across the nodes, which is the most optimized. Otherwise, each node keeps 1 example out of `world_size`, skipping the other examples.

**datasets.enable\_caching**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/fingerprint.py#L96)

( )

When applying transforms on a dataset, the data are stored in cache files. The caching mechanism allows to reload an existing cache file if it’s already been computed.

Reloading a dataset is possible since the cache files are named using the dataset fingerprint, which is updated after each transform.

If disabled, the library will no longer reload cached datasets files when applying transforms to the datasets. More precisely, if the caching is disabled:

* cache files are always recreated
* cache files are written to a temporary directory that is deleted when session closes
* cache files are named using a random hash instead of the dataset fingerprint
* use [save\_to\_disk()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.save_to_disk) to save a transformed dataset or it will be deleted when session closes
* caching doesn’t affect [load\_dataset()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/loading_methods#datasets.load_dataset). If you want to regenerate a dataset from scratch you should use the `download_mode` parameter in [load\_dataset()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/loading_methods#datasets.load_dataset).

**datasets.disable\_caching**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/fingerprint.py#L117)

( )

When applying transforms on a dataset, the data are stored in cache files. The caching mechanism allows to reload an existing cache file if it’s already been computed.

Reloading a dataset is possible since the cache files are named using the dataset fingerprint, which is updated after each transform.

If disabled, the library will no longer reload cached datasets files when applying transforms to the datasets. More precisely, if the caching is disabled:

* cache files are always recreated
* cache files are written to a temporary directory that is deleted when session closes
* cache files are named using a random hash instead of the dataset fingerprint
* use [save\_to\_disk()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.save_to_disk) to save a transformed dataset or it will be deleted when session closes
* caching doesn’t affect [load\_dataset()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/loading_methods#datasets.load_dataset). If you want to regenerate a dataset from scratch you should use the `download_mode` parameter in [load\_dataset()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/loading_methods#datasets.load_dataset).

**datasets.is\_caching\_enabled**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/fingerprint.py#L162)

( )

When applying transforms on a dataset, the data are stored in cache files. The caching mechanism allows to reload an existing cache file if it’s already been computed.

Reloading a dataset is possible since the cache files are named using the dataset fingerprint, which is updated after each transform.

If disabled, the library will no longer reload cached datasets files when applying transforms to the datasets. More precisely, if the caching is disabled:

* cache files are always recreated
* cache files are written to a temporary directory that is deleted when session closes
* cache files are named using a random hash instead of the dataset fingerprint
* use [save\_to\_disk()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.save_to_disk)] to save a transformed dataset or it will be deleted when session closes
* caching doesn’t affect [load\_dataset()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/loading_methods#datasets.load_dataset). If you want to regenerate a dataset from scratch you should use the `download_mode` parameter in [load\_dataset()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/loading_methods#datasets.load_dataset).

### DatasetDict

Dictionary with split names as keys (‘train’, ‘test’ for example), and `Dataset` objects as values. It also has dataset transform methods like map or filter, to process all the splits at once.

#### class datasets.DatasetDict

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L41)

( )

A dictionary (dict of str: datasets.Dataset) with dataset transforms methods (map, filter, etc.)

**data**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L71)

( )

The Apache Arrow tables backing each split.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.data
```

**cache\_files**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L86)

( )

The cache files containing the Apache Arrow table backing each split.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.cache_files
{'test': [{'filename': '/root/.cache/boincai/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-test.arrow'}],
 'train': [{'filename': '/root/.cache/boincai/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-train.arrow'}],
 'validation': [{'filename': '/root/.cache/boincai/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-validation.arrow'}]}
```

**num\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L104)

( )

Number of columns in each split of the dataset.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.num_columns
{'test': 2, 'train': 2, 'validation': 2}
```

**num\_rows**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L120)

( )

Number of rows in each split of the dataset (same as [datasets.Dataset.**len**()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.__len__)).

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.num_rows
{'test': 1066, 'train': 8530, 'validation': 1066}
```

**column\_names**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L136)

( )

Names of the columns in each split of the dataset.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.column_names
{'test': ['text', 'label'],
 'train': ['text', 'label'],
 'validation': ['text', 'label']}
```

**shape**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L154)

( )

Shape of each split of the dataset (number of columns, number of rows).

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.shape
{'test': (1066, 2), 'train': (8530, 2), 'validation': (1066, 2)}
```

**unique**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L202)

( column: str ) → Dict\[`str`, `list`]

Parameters

* **column** (`str`) — column name (list all the column names with [column\_names](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.column_names))

Returns

Dict\[`str`, `list`]

Dictionary of unique elements in the given column.

Return a list of the unique elements in a column for each split.

This is implemented in the low-level backend and as such, very fast.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.unique("label")
{'test': [1, 0], 'train': [1, 0], 'validation': [1, 0]}
```

**cleanup\_cache\_files**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L226)

( )

Clean up all cache files in the dataset cache directory, excepted the currently used cache file if there is one. Be careful when running this command that no other process is currently using other cache files.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.cleanup_cache_files()
{'test': 0, 'train': 0, 'validation': 0}
```

**map**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L749)

( function: typing.Optional\[typing.Callable] = Nonewith\_indices: bool = Falsewith\_rank: bool = Falseinput\_columns: typing.Union\[str, typing.List\[str], NoneType] = Nonebatched: bool = Falsebatch\_size: typing.Optional\[int] = 1000drop\_last\_batch: bool = Falseremove\_columns: typing.Union\[str, typing.List\[str], NoneType] = Nonekeep\_in\_memory: bool = Falseload\_from\_cache\_file: typing.Optional\[bool] = Nonecache\_file\_names: typing.Union\[typing.Dict\[str, typing.Optional\[str]], NoneType] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000features: typing.Optional\[datasets.features.features.Features] = Nonedisable\_nullable: bool = Falsefn\_kwargs: typing.Optional\[dict] = Nonenum\_proc: typing.Optional\[int] = Nonedesc: typing.Optional\[str] = None )

Parameters

* **function** (`callable`) — with one of the following signature:

  * `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` and `with_indices=False`
  * `function(example: Dict[str, Any], indices: int) -> Dict[str, Any]` if `batched=False` and `with_indices=True`
  * `function(batch: Dict[str, List]) -> Dict[str, List]` if `batched=True` and `with_indices=False`
  * `function(batch: Dict[str, List], indices: List[int]) -> Dict[str, List]` if `batched=True` and `with_indices=True`

  For advanced usage, the function can also return a `pyarrow.Table`. Moreover if your function returns nothing (`None`), then `map` will run your function and return the dataset unchanged.
* **with\_indices** (`bool`, defaults to `False`) — Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`.
* **with\_rank** (`bool`, defaults to `False`) — Provide process rank to `function`. Note that in this case the signature of `function` should be `def function(example[, idx], rank): ...`.
* **input\_columns** (`[Union[str, List[str]]]`, *optional*, defaults to `None`) — The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument.
* **batched** (`bool`, defaults to `False`) — Provide batch of examples to `function`.
* **batch\_size** (`int`, *optional*, defaults to `1000`) — Number of examples per batch provided to `function` if `batched=True`, `batch_size <= 0` or `batch_size == None` then provide the full dataset as a single batch to `function`.
* **drop\_last\_batch** (`bool`, defaults to `False`) — Whether a last batch smaller than the batch\_size should be dropped instead of being processed by the function.
* **remove\_columns** (`[Union[str, List[str]]]`, *optional*, defaults to `None`) — Remove a selection of columns while doing the mapping. Columns will be removed before updating the examples with the output of `function`, i.e. if `function` is adding columns with names in `remove_columns`, these columns will be kept.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Keep the dataset in memory instead of writing it to a cache file.
* **load\_from\_cache\_file** (`Optional[bool]`, defaults to `True` if caching is enabled) — If a cache file storing the current computation from `function` can be identified, use it instead of recomputing.
* **cache\_file\_names** (`[Dict[str, str]]`, *optional*, defaults to `None`) — Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name. You have to provide one `cache_file_name` per dataset in the dataset dictionary.
* **writer\_batch\_size** (`int`, default `1000`) — Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`.
* **features** (`[datasets.Features]`, *optional*, defaults to `None`) — Use a specific [Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features) to store the cache file instead of the automatically generated one.
* **disable\_nullable** (`bool`, defaults to `False`) — Disallow null values in the table.
* **fn\_kwargs** (`Dict`, *optional*, defaults to `None`) — Keyword arguments to be passed to `function`
* **num\_proc** (`int`, *optional*, defaults to `None`) — Number of processes for multiprocessing. By default it doesn’t use multiprocessing.
* **desc** (`str`, *optional*, defaults to `None`) — Meaningful description to be displayed alongside with the progress bar while mapping examples.

Apply a function to all the elements in the table (individually or in batches) and update the table (if function does updated examples). The transformation is applied to all the datasets of the dataset dictionary.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> def add_prefix(example):
...     example["text"] = "Review: " + example["text"]
...     return example
>>> ds = ds.map(add_prefix)
>>> ds["train"][0:3]["text"]
['Review: the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .',
 'Review: the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .',
 'Review: effective but too-tepid biopic']

# process a batch of examples
>>> ds = ds.map(lambda example: tokenizer(example["text"]), batched=True)
# set number of processors
>>> ds = ds.map(add_prefix, num_proc=4)
```

**filter**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L877)

( functionwith\_indices = Falseinput\_columns: typing.Union\[str, typing.List\[str], NoneType] = Nonebatched: bool = Falsebatch\_size: typing.Optional\[int] = 1000keep\_in\_memory: bool = Falseload\_from\_cache\_file: typing.Optional\[bool] = Nonecache\_file\_names: typing.Union\[typing.Dict\[str, typing.Optional\[str]], NoneType] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000fn\_kwargs: typing.Optional\[dict] = Nonenum\_proc: typing.Optional\[int] = Nonedesc: typing.Optional\[str] = None )

Parameters

* **function** (`callable`) — With one of the following signature:
  * `function(example: Dict[str, Any]) -> bool` if `with_indices=False, batched=False`
  * `function(example: Dict[str, Any], indices: int) -> bool` if `with_indices=True, batched=False`
  * `function(example: Dict[str, List]) -> List[bool]` if `with_indices=False, batched=True`
  * `function(example: Dict[str, List], indices: List[int]) -> List[bool]` if \``with_indices=True, batched=True`
* **with\_indices** (`bool`, defaults to `False`) — Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`.
* **input\_columns** (`[Union[str, List[str]]]`, *optional*, defaults to `None`) — The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument.
* **batched** (`bool`, defaults to `False`) — Provide batch of examples to `function`.
* **batch\_size** (`int`, *optional*, defaults to `1000`) — Number of examples per batch provided to `function` if `batched=True` `batch_size <= 0` or `batch_size == None` then provide the full dataset as a single batch to `function`.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Keep the dataset in memory instead of writing it to a cache file.
* **load\_from\_cache\_file** (`Optional[bool]`, defaults to `True` if chaching is enabled) — If a cache file storing the current computation from `function` can be identified, use it instead of recomputing.
* **cache\_file\_names** (`[Dict[str, str]]`, *optional*, defaults to `None`) — Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name. You have to provide one `cache_file_name` per dataset in the dataset dictionary.
* **writer\_batch\_size** (`int`, defaults to `1000`) — Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`.
* **fn\_kwargs** (`Dict`, *optional*, defaults to `None`) — Keyword arguments to be passed to `function`
* **num\_proc** (`int`, *optional*, defaults to `None`) — Number of processes for multiprocessing. By default it doesn’t use multiprocessing.
* **desc** (`str`, *optional*, defaults to `None`) — Meaningful description to be displayed alongside with the progress bar while filtering examples.

Apply a filter function to all the elements in the table in batches and update the table so that the dataset only includes examples according to the filter function. The transformation is applied to all the datasets of the dataset dictionary.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.filter(lambda x: x["label"] == 1)
DatasetDict({
    train: Dataset({
        features: ['text', 'label'],
        num_rows: 4265
    })
    validation: Dataset({
        features: ['text', 'label'],
        num_rows: 533
    })
    test: Dataset({
        features: ['text', 'label'],
        num_rows: 533
    })
})
```

**sort**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1031)

( column\_names: typing.Union\[str, typing.Sequence\[str]]reverse: typing.Union\[bool, typing.Sequence\[bool]] = Falsekind = 'deprecated'null\_placement: str = 'at\_end'keep\_in\_memory: bool = Falseload\_from\_cache\_file: typing.Optional\[bool] = Noneindices\_cache\_file\_names: typing.Union\[typing.Dict\[str, typing.Optional\[str]], NoneType] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000 )

Parameters

* **column\_names** (`Union[str, Sequence[str]]`) — Column name(s) to sort by.
* **reverse** (`Union[bool, Sequence[bool]]`, defaults to `False`) — If `True`, sort by descending order rather than ascending. If a single bool is provided, the value is applied to the sorting of all column names. Otherwise a list of bools with the same length and order as column\_names must be provided.
* **kind** (`str`, *optional*) — Pandas algorithm for sorting selected in `{quicksort, mergesort, heapsort, stable}`, The default is `quicksort`. Note that both `stable` and `mergesort` use timsort under the covers and, in general, the actual implementation will vary with data type. The `mergesort` option is retained for backwards compatibility.

  Deprecated in 2.8.0

  `kind` was deprecated in version 2.10.0 and will be removed in 3.0.0.
* **null\_placement** (`str`, defaults to `at_end`) — Put `None` values at the beginning if `at_start` or `first` or at the end if `at_end` or `last`
* **keep\_in\_memory** (`bool`, defaults to `False`) — Keep the sorted indices in memory instead of writing it to a cache file.
* **load\_from\_cache\_file** (`Optional[bool]`, defaults to `True` if caching is enabled) — If a cache file storing the sorted indices can be identified, use it instead of recomputing.
* **indices\_cache\_file\_names** (`[Dict[str, str]]`, *optional*, defaults to `None`) — Provide the name of a path for the cache file. It is used to store the indices mapping instead of the automatically generated cache file name. You have to provide one `cache_file_name` per dataset in the dataset dictionary.
* **writer\_batch\_size** (`int`, defaults to `1000`) — Number of rows per write operation for the cache file writer. Higher value gives smaller cache files, lower value consume less temporary memory.

Create a new dataset sorted according to a single or multiple columns.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset('rotten_tomatoes')
>>> ds['train']['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>>> sorted_ds = ds.sort('label')
>>> sorted_ds['train']['label'][:10]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> another_sorted_ds = ds.sort(['label', 'text'], reverse=[True, False])
>>> another_sorted_ds['train']['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
```

**shuffle**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1109)

( seeds: typing.Union\[int, typing.Dict\[str, typing.Optional\[int]], NoneType] = Noneseed: typing.Optional\[int] = Nonegenerators: typing.Union\[typing.Dict\[str, numpy.random.\_generator.Generator], NoneType] = Nonekeep\_in\_memory: bool = Falseload\_from\_cache\_file: typing.Optional\[bool] = Noneindices\_cache\_file\_names: typing.Union\[typing.Dict\[str, typing.Optional\[str]], NoneType] = Nonewriter\_batch\_size: typing.Optional\[int] = 1000 )

Parameters

* **seeds** (`Dict[str, int]` or `int`, *optional*) — A seed to initialize the default BitGenerator if `generator=None`. If `None`, then fresh, unpredictable entropy will be pulled from the OS. If an `int` or `array_like[ints]` is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. You can provide one `seed` per dataset in the dataset dictionary.
* **seed** (`int`, *optional*) — A seed to initialize the default BitGenerator if `generator=None`. Alias for seeds (a `ValueError` is raised if both are provided).
* **generators** (`Dict[str, *optional*, np.random.Generator]`) — Numpy random Generator to use to compute the permutation of the dataset rows. If `generator=None` (default), uses `np.random.default_rng` (the default BitGenerator (PCG64) of NumPy). You have to provide one `generator` per dataset in the dataset dictionary.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Keep the dataset in memory instead of writing it to a cache file.
* **load\_from\_cache\_file** (`Optional[bool]`, defaults to `True` if caching is enabled) — If a cache file storing the current computation from `function` can be identified, use it instead of recomputing.
* **indices\_cache\_file\_names** (`Dict[str, str]`, *optional*) — Provide the name of a path for the cache file. It is used to store the indices mappings instead of the automatically generated cache file name. You have to provide one `cache_file_name` per dataset in the dataset dictionary.
* **writer\_batch\_size** (`int`, defaults to `1000`) — Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`.

Create a new Dataset where the rows are shuffled.

The transformation is applied to all the datasets of the dataset dictionary.

Currently shuffling uses numpy random generators. You can either supply a NumPy BitGenerator to use, or a seed to initiate NumPy’s default random generator (PCG64).

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds["train"]["label"][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

# set a seed
>>> shuffled_ds = ds.shuffle(seed=42)
>>> shuffled_ds["train"]["label"][:10]
[0, 1, 0, 1, 0, 0, 0, 0, 0, 0]
```

**set\_format**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L541)

( type: typing.Optional\[str] = Nonecolumns: typing.Optional\[typing.List] = Noneoutput\_all\_columns: bool = False\*\*format\_kwargs )

Parameters

* **type** (`str`, *optional*) — Output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default).
* **columns** (`List[str]`, *optional*) — Columns to format in the output. `None` means `__getitem__` returns all columns (default).
* **output\_all\_columns** (`bool`, defaults to False) — Keep un-formatted columns as well in the output (as python objects),
* \***\*format\_kwargs** (additional keyword arguments) — Keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`.

Set `__getitem__` return format (type and columns). The format is set for every dataset in the dataset dictionary.

It is possible to call `map` after calling `set_format`. Since `map` may add new columns, then the list of formatted columns gets updated. In this case, if you apply `map` on a dataset to add a new column, then this column will be formatted:

`new formatted columns = (all columns - previously unformatted columns)`

Example:

Copied

```
>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x["text"], truncation=True, padding=True), batched=True)
>>> ds.set_format(type="numpy", columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
>>> ds["train"].format
{'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'numpy'}
```

**reset\_format**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L587)

( )

Reset `__getitem__` return format to python objects and all columns. The transformation is applied to all the datasets of the dataset dictionary.

Same as `self.set_format()`

Example:

Copied

```
>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("rotten_tomatoes")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x["text"], truncation=True, padding=True), batched=True)
>>> ds.set_format(type="numpy", columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
>>> ds["train"].format
{'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'numpy'}
>>> ds.reset_format()
>>> ds["train"].format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': None}
```

**formatted\_as**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L504)

( type: typing.Optional\[str] = Nonecolumns: typing.Optional\[typing.List] = Noneoutput\_all\_columns: bool = False\*\*format\_kwargs )

Parameters

* **type** (`str`, *optional*) — Output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default).
* **columns** (`List[str]`, *optional*) — Columns to format in the output. `None` means `__getitem__` returns all columns (default).
* **output\_all\_columns** (`bool`, defaults to False) — Keep un-formatted columns as well in the output (as python objects).
* \***\*format\_kwargs** (additional keyword arguments) — Keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`.

To be used in a `with` statement. Set `__getitem__` return format (type and columns). The transformation is applied to all the datasets of the dataset dictionary.

**with\_format**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L643)

( type: typing.Optional\[str] = Nonecolumns: typing.Optional\[typing.List] = Noneoutput\_all\_columns: bool = False\*\*format\_kwargs )

Parameters

* **type** (`str`, *optional*) — Output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default).
* **columns** (`List[str]`, *optional*) — Columns to format in the output. `None` means `__getitem__` returns all columns (default).
* **output\_all\_columns** (`bool`, defaults to `False`) — Keep un-formatted columns as well in the output (as python objects).
* \***\*format\_kwargs** (additional keyword arguments) — Keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`.

Set `__getitem__` return format (type and columns). The data formatting is applied on-the-fly. The format `type` (for example “numpy”) is used to format batches when using `__getitem__`. The format is set for every dataset in the dataset dictionary.

It’s also possible to use custom transforms for formatting using [with\_transform()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.with_transform).

Contrary to [set\_format()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict.set_format), `with_format` returns a new [DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict) object with new [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) objects.

Example:

Copied

```
>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("rotten_tomatoes")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds["train"].format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': None}
>>> ds = ds.with_format(type='tensorflow', columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
>>> ds["train"].format
{'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'tensorflow'}
```

**with\_transform**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L695)

( transform: typing.Optional\[typing.Callable]columns: typing.Optional\[typing.List] = Noneoutput\_all\_columns: bool = False )

Parameters

* **transform** (`Callable`, *optional*) — User-defined formatting transform, replaces the format defined by [set\_format()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.set_format). A formatting function is a callable that takes a batch (as a dict) as input and returns a batch. This function is applied right before returning the objects in `__getitem__`.
* **columns** (`List[str]`, *optional*) — Columns to format in the output. If specified, then the input batch of the transform only contains those columns.
* **output\_all\_columns** (`bool`, defaults to False) — Keep un-formatted columns as well in the output (as python objects). If set to `True`, then the other un-formatted columns are kept with the output of the transform.

Set `__getitem__` return format using this transform. The transform is applied on-the-fly on batches when `__getitem__` is called. The transform is set for every dataset in the dataset dictionary

As [set\_format()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.set_format), this can be reset using [reset\_format()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.reset_format).

Contrary to `set_transform()`, `with_transform` returns a new [DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict) object with new [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset) objects.

Example:

Copied

```
>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("rotten_tomatoes")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> def encode(example):
...     return tokenizer(example['text'], truncation=True, padding=True, return_tensors="pt")
>>> ds = ds.with_transform(encode)
>>> ds["train"][0]
{'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
 1, 1, 1, 1, 1, 1, 1, 1, 1]),
 'input_ids': tensor([  101,  1103,  2067,  1110, 17348,  1106,  1129,  1103,  6880,  1432,
        112,   188,  1207,   107, 14255,  1389,   107,  1105,  1115,  1119,
        112,   188,  1280,  1106,  1294,   170, 24194,  1256,  3407,  1190,
        170, 11791,  5253,   188,  1732,  7200, 10947, 12606,  2895,   117,
        179,  7766,   118,   172, 15554,  1181,  3498,  6961,  3263,  1137,
        188,  1566,  7912, 14516,  6997,   119,   102]),
 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0])}
```

**flatten**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L170)

( max\_depth = 16 )

Flatten the Apache Arrow Table of each split (nested features are flatten). Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("squad")
>>> ds["train"].features
{'answers': Sequence(feature={'text': Value(dtype='string', id=None), 'answer_start': Value(dtype='int32', id=None)}, length=-1, id=None),
 'context': Value(dtype='string', id=None),
 'id': Value(dtype='string', id=None),
 'question': Value(dtype='string', id=None),
 'title': Value(dtype='string', id=None)}
>>> ds.flatten()
DatasetDict({
    train: Dataset({
        features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'],
        num_rows: 87599
    })
    validation: Dataset({
        features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'],
        num_rows: 10570
    })
})
```

**cast**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L250)

( features: Features )

Parameters

* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features)) — New features to cast the dataset to. The name and order of the fields in the features must match the current column names. The type of the data must also be convertible from one type to the other. For non-trivial conversion, e.g. `string` <-> `ClassLabel` you should use [map()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.map) to update the Dataset.

Cast the dataset to a new set of features. The transformation is applied to all the datasets of the dataset dictionary.

You can also remove a column using [Dataset.map()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.map) with `feature` but `cast` is in-place (doesn’t copy the data to a new dataset) and is thus faster.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds["train"].features
{'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None),
 'text': Value(dtype='string', id=None)}
>>> new_features = ds["train"].features.copy()
>>> new_features['label'] = ClassLabel(names=['bad', 'good'])
>>> new_features['text'] = Value('large_string')
>>> ds = ds.cast(new_features)
>>> ds["train"].features
{'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None),
 'text': Value(dtype='large_string', id=None)}
```

**cast\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L285)

( column: strfeature )

Parameters

* **column** (`str`) — Column name.
* **feature** (`Feature`) — Target feature.

Cast column to feature for decoding.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds["train"].features
{'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None),
 'text': Value(dtype='string', id=None)}
>>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good']))
>>> ds["train"].features
{'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None),
 'text': Value(dtype='string', id=None)}
```

**remove\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L314)

( column\_names: typing.Union\[str, typing.List\[str]] )

Parameters

* **column\_names** (`Union[str, List[str]]`) — Name of the column(s) to remove.

Remove one or several column(s) from each split in the dataset and the features associated to the column(s).

The transformation is applied to all the splits of the dataset dictionary.

You can also remove a column using [Dataset.map()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.map) with `remove_columns` but the present method is in-place (doesn’t copy the data to a new dataset) and is thus faster.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.remove_columns("label")
DatasetDict({
    train: Dataset({
        features: ['text'],
        num_rows: 8530
    })
    validation: Dataset({
        features: ['text'],
        num_rows: 1066
    })
    test: Dataset({
        features: ['text'],
        num_rows: 1066
    })
})
```

**rename\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L353)

( original\_column\_name: strnew\_column\_name: str )

Parameters

* **original\_column\_name** (`str`) — Name of the column to rename.
* **new\_column\_name** (`str`) — New name for the column.

Rename a column in the dataset and move the features associated to the original column under the new column name. The transformation is applied to all the datasets of the dataset dictionary.

You can also rename a column using [map()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.map) with `remove_columns` but the present method:

* takes care of moving the original features under the new column name.
* doesn’t copy the data to a new dataset and is thus much faster.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.rename_column("label", "label_new")
DatasetDict({
    train: Dataset({
        features: ['text', 'label_new'],
        num_rows: 8530
    })
    validation: Dataset({
        features: ['text', 'label_new'],
        num_rows: 1066
    })
    test: Dataset({
        features: ['text', 'label_new'],
        num_rows: 1066
    })
})
```

**rename\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L398)

( column\_mapping: typing.Dict\[str, str] ) → [DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict)

Parameters

* **column\_mapping** (`Dict[str, str]`) — A mapping of columns to rename to their new names.

Returns

[DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict)

A copy of the dataset with renamed columns.

Rename several columns in the dataset, and move the features associated to the original columns under the new column names. The transformation is applied to all the datasets of the dataset dictionary.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.rename_columns({'text': 'text_new', 'label': 'label_new'})
DatasetDict({
    train: Dataset({
        features: ['text_new', 'label_new'],
        num_rows: 8530
    })
    validation: Dataset({
        features: ['text_new', 'label_new'],
        num_rows: 1066
    })
    test: Dataset({
        features: ['text_new', 'label_new'],
        num_rows: 1066
    })
})
```

**select\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L436)

( column\_names: typing.Union\[str, typing.List\[str]] )

Parameters

* **column\_names** (`Union[str, List[str]]`) — Name of the column(s) to keep.

Select one or several column(s) from each split in the dataset and the features associated to the column(s).

The transformation is applied to all the splits of the dataset dictionary.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.select_columns("text")
DatasetDict({
    train: Dataset({
        features: ['text'],
        num_rows: 8530
    })
    validation: Dataset({
        features: ['text'],
        num_rows: 1066
    })
    test: Dataset({
        features: ['text'],
        num_rows: 1066
    })
})
```

**class\_encode\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L472)

( column: strinclude\_nulls: bool = False )

Parameters

* **column** (`str`) — The name of the column to cast.
* **include\_nulls** (`bool`, defaults to `False`) — Whether to include null values in the class labels. If `True`, the null values will be encoded as the `"None"` class label.

  Added in 1.14.2

Casts the given column as [ClassLabel](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.ClassLabel) and updates the tables.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("boolq")
>>> ds["train"].features
{'answer': Value(dtype='bool', id=None),
 'passage': Value(dtype='string', id=None),
 'question': Value(dtype='string', id=None)}
>>> ds = ds.class_encode_column("answer")
>>> ds["train"].features
{'answer': ClassLabel(num_classes=2, names=['False', 'True'], id=None),
 'passage': Value(dtype='string', id=None),
 'question': Value(dtype='string', id=None)}
```

**push\_to\_hub**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1558)

( repo\_idconfig\_name: str = 'default'private: typing.Optional\[bool] = Falsetoken: typing.Optional\[str] = Nonebranch: NoneType = Nonemax\_shard\_size: typing.Union\[str, int, NoneType] = Nonenum\_shards: typing.Union\[typing.Dict\[str, int], NoneType] = Noneembed\_external\_files: bool = True )

Parameters

* **repo\_id** (`str`) — The ID of the repository to push to in the following format: `<user>/<dataset_name>` or `<org>/<dataset_name>`. Also accepts `<dataset_name>`, which will default to the namespace of the logged-in user.
* **private** (`bool`, *optional*) — Whether the dataset repository should be set to private or not. Only affects repository creation: a repository that already exists will not be affected by that parameter.
* **config\_name** (`str`) — Configuration name of a dataset. Defaults to “default”.
* **token** (`str`, *optional*) — An optional authentication token for the BOINC AI Hub. If no token is passed, will default to the token saved locally when logging in with `boincai-cli login`. Will raise an error if no token is passed and the user is not logged-in.
* **branch** (`str`, *optional*) — The git branch on which to push the dataset.
* **max\_shard\_size** (`int` or `str`, *optional*, defaults to `"500MB"`) — The maximum size of the dataset shards to be uploaded to the hub. If expressed as a string, needs to be digits followed by a unit (like `"500MB"` or `"1GB"`).
* **num\_shards** (`Dict[str, int]`, *optional*) — Number of shards to write. By default the number of shards depends on `max_shard_size`. Use a dictionary to define a different num\_shards for each split.

  Added in 2.8.0
* **embed\_external\_files** (`bool`, defaults to `True`) — Whether to embed file bytes in the shards. In particular, this will do the following before the push for the fields of type:
  * [Audio](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Audio) and [Image](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Image) removes local path information and embed file content in the Parquet files.

Pushes the [DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict) to the hub as a Parquet dataset. The [DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict) is pushed using HTTP requests and does not need to have neither git or git-lfs installed.

Each dataset split will be pushed independently. The pushed dataset will keep the original split names.

The resulting Parquet files are self-contained by default: if your dataset contains [Image](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Image) or [Audio](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Audio) data, the Parquet files will store the bytes of your images or audio files. You can disable this by setting `embed_external_files` to False.

Example:

Copied

```
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>")
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", private=True)
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", max_shard_size="1GB")
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", num_shards={"train": 1024, "test": 8})
```

**save\_to\_disk**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1192)

( dataset\_dict\_path: typing.Union\[str, bytes, os.PathLike]fs = 'deprecated'max\_shard\_size: typing.Union\[str, int, NoneType] = Nonenum\_shards: typing.Union\[typing.Dict\[str, int], NoneType] = Nonenum\_proc: typing.Optional\[int] = Nonestorage\_options: typing.Optional\[dict] = None )

Parameters

* **dataset\_dict\_path** (`str`) — Path (e.g. `dataset/train`) or remote URI (e.g. `s3://my-bucket/dataset/train`) of the dataset dict directory where the dataset dict will be saved to.
* **fs** (`fsspec.spec.AbstractFileSystem`, *optional*) — Instance of the remote filesystem where the dataset will be saved to.

  Deprecated in 2.8.0

  `fs` was deprecated in version 2.8.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options`
* **max\_shard\_size** (`int` or `str`, *optional*, defaults to `"500MB"`) — The maximum size of the dataset shards to be uploaded to the hub. If expressed as a string, needs to be digits followed by a unit (like `"50MB"`).
* **num\_shards** (`Dict[str, int]`, *optional*) — Number of shards to write. By default the number of shards depends on `max_shard_size` and `num_proc`. You need to provide the number of shards for each dataset in the dataset dictionary. Use a dictionary to define a different num\_shards for each split.

  Added in 2.8.0
* **num\_proc** (`int`, *optional*, default `None`) — Number of processes when downloading and generating the dataset locally. Multiprocessing is disabled by default.

  Added in 2.8.0
* **storage\_options** (`dict`, *optional*) — Key/value pairs to be passed on to the file-system backend, if any.

  Added in 2.8.0

Saves a dataset dict to a filesystem using `fsspec.spec.AbstractFileSystem`.

For [Image](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Image) and [Audio](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Audio) data:

All the Image() and Audio() data are stored in the arrow files. If you want to store paths or urls, please use the Value(“string”) type.

Example:

Copied

```
>>> dataset_dict.save_to_disk("path/to/dataset/directory")
>>> dataset_dict.save_to_disk("path/to/dataset/directory", max_shard_size="1GB")
>>> dataset_dict.save_to_disk("path/to/dataset/directory", num_shards={"train": 1024, "test": 8})
```

**load\_from\_disk**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1287)

( dataset\_dict\_path: typing.Union\[str, bytes, os.PathLike]fs = 'deprecated'keep\_in\_memory: typing.Optional\[bool] = Nonestorage\_options: typing.Optional\[dict] = None )

Parameters

* **dataset\_dict\_path** (`str`) — Path (e.g. `"dataset/train"`) or remote URI (e.g. `"s3//my-bucket/dataset/train"`) of the dataset dict directory where the dataset dict will be loaded from.
* **fs** (`fsspec.spec.AbstractFileSystem`, *optional*) — Instance of the remote filesystem where the dataset will be saved to.

  Deprecated in 2.8.0

  `fs` was deprecated in version 2.8.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options`
* **keep\_in\_memory** (`bool`, defaults to `None`) — Whether to copy the dataset in-memory. If `None`, the dataset will not be copied in-memory unless explicitly enabled by setting `datasets.config.IN_MEMORY_MAX_SIZE` to nonzero. See more details in the [improve performance](https://huggingface.co/docs/datasets/cache#improve-performance) section.
* **storage\_options** (`dict`, *optional*) — Key/value pairs to be passed on to the file-system backend, if any.

  Added in 2.8.0

Load a dataset that was previously saved using `save_to_disk` from a filesystem using `fsspec.spec.AbstractFileSystem`.

Example:

Copied

```
>>> ds = load_from_disk('path/to/dataset/directory')
```

**from\_csv**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1376)

( path\_or\_paths: typing.Dict\[str, typing.Union\[str, bytes, os.PathLike]]features: typing.Optional\[datasets.features.features.Features] = Nonecache\_dir: str = Nonekeep\_in\_memory: bool = False\*\*kwargs )

Parameters

* **path\_or\_paths** (`dict` of path-like) — Path(s) of the CSV file(s).
* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features), *optional*) — Dataset features.
* **cache\_dir** (str, *optional*, defaults to `"~/.cache/boincai/datasets"`) — Directory to cache data.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.
* \***\*kwargs** (additional keyword arguments) — Keyword arguments to be passed to `pandas.read_csv`.

Create [DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict) from CSV file(s).

Example:

Copied

```
>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_csv({'train': 'path/to/dataset.csv'})
```

**from\_json**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1415)

( path\_or\_paths: typing.Dict\[str, typing.Union\[str, bytes, os.PathLike]]features: typing.Optional\[datasets.features.features.Features] = Nonecache\_dir: str = Nonekeep\_in\_memory: bool = False\*\*kwargs )

Parameters

* **path\_or\_paths** (`path-like` or list of `path-like`) — Path(s) of the JSON Lines file(s).
* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features), *optional*) — Dataset features.
* **cache\_dir** (str, *optional*, defaults to `"~/.cache/boincai/datasets"`) — Directory to cache data.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.
* \***\*kwargs** (additional keyword arguments) — Keyword arguments to be passed to `JsonConfig`.

Create [DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict) from JSON Lines file(s).

Example:

Copied

```
>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_json({'train': 'path/to/dataset.json'})
```

**from\_parquet**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1454)

( path\_or\_paths: typing.Dict\[str, typing.Union\[str, bytes, os.PathLike]]features: typing.Optional\[datasets.features.features.Features] = Nonecache\_dir: str = Nonekeep\_in\_memory: bool = Falsecolumns: typing.Optional\[typing.List\[str]] = None\*\*kwargs )

Parameters

* **path\_or\_paths** (`dict` of path-like) — Path(s) of the CSV file(s).
* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features), *optional*) — Dataset features.
* **cache\_dir** (`str`, *optional*, defaults to `"~/.cache/boincai/datasets"`) — Directory to cache data.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.
* **columns** (`List[str]`, *optional*) — If not `None`, only these columns will be read from the file. A column name may be a prefix of a nested field, e.g. ‘a’ will select ‘a.b’, ‘a.c’, and ‘a.d.e’.
* \***\*kwargs** (additional keyword arguments) — Keyword arguments to be passed to `ParquetConfig`.

Create [DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict) from Parquet file(s).

Example:

Copied

```
>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_parquet({'train': 'path/to/dataset/parquet'})
```

**from\_text**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1503)

( path\_or\_paths: typing.Dict\[str, typing.Union\[str, bytes, os.PathLike]]features: typing.Optional\[datasets.features.features.Features] = Nonecache\_dir: str = Nonekeep\_in\_memory: bool = False\*\*kwargs )

Parameters

* **path\_or\_paths** (`dict` of path-like) — Path(s) of the text file(s).
* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features), *optional*) — Dataset features.
* **cache\_dir** (`str`, *optional*, defaults to `"~/.cache/boincai/datasets"`) — Directory to cache data.
* **keep\_in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.
* \***\*kwargs** (additional keyword arguments) — Keyword arguments to be passed to `TextConfig`.

Create [DatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetDict) from text file(s).

Example:

Copied

```
>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_text({'train': 'path/to/dataset.txt'})
```

**prepare\_for\_task**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1542)

( task: typing.Union\[str, datasets.tasks.base.TaskTemplate]id: int = 0 )

Parameters

* **task** (`Union[str, TaskTemplate]`) — The task to prepare the dataset for during training and evaluation. If `str`, supported tasks include:

  * `"text-classification"`
  * `"question-answering"`

  If `TaskTemplate`, must be one of the task templates in [`datasets.tasks`](https://huggingface.co/docs/datasets/package_reference/task_templates).
* **id** (`int`, defaults to `0`) — The id required to unambiguously identify the task template when multiple task templates of the same type are supported.

Prepare a dataset for the given task by casting the dataset’s [Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features) to standardized column names and types as detailed in [`datasets.tasks`](https://huggingface.co/docs/datasets/package_reference/task_templates).

Casts `datasets.DatasetInfo.features` according to a task-specific schema. Intended for single-use only, so all task templates are removed from `datasets.DatasetInfo.task_templates` after casting.

### IterableDataset

The base class [IterableDataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset) implements an iterable Dataset backed by python generators.

#### class datasets.IterableDataset

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L1185)

( ex\_iterable: \_BaseExamplesIterableinfo: typing.Optional\[datasets.info.DatasetInfo] = Nonesplit: typing.Optional\[datasets.splits.NamedSplit] = Noneformatting: typing.Optional\[datasets.iterable\_dataset.FormattingConfig] = Noneshuffling: typing.Optional\[datasets.iterable\_dataset.ShufflingConfig] = Nonedistributed: typing.Optional\[datasets.iterable\_dataset.DistributedConfig] = Nonetoken\_per\_repo\_id: typing.Union\[typing.Dict\[str, typing.Union\[str, bool, NoneType]], NoneType] = Noneformat\_type = 'deprecated' )

A Dataset backed by an iterable.

**from\_generator**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L1430)

( generator: typing.Callablefeatures: typing.Optional\[datasets.features.features.Features] = Nonegen\_kwargs: typing.Optional\[dict] = None ) → `IterableDataset`

Parameters

* **generator** (`Callable`) — A generator function that `yields` examples.
* **features** (`Features`, *optional*) — Dataset features.
* **gen\_kwargs(`dict`,** *optional*) — Keyword arguments to be passed to the `generator` callable. You can define a sharded iterable dataset by passing the list of shards in `gen_kwargs`. This can be used to improve shuffling and when iterating over the dataset with multiple workers.

Returns

`IterableDataset`

Create an Iterable Dataset from a generator.

Example:

Copied

```
>>> def gen():
...     yield {"text": "Good", "label": 0}
...     yield {"text": "Bad", "label": 1}
...
>>> ds = IterableDataset.from_generator(gen)
```

Copied

```
>>> def gen(shards):
...     for shard in shards:
...         with open(shard) as f:
...             for line in f:
...                 yield {"line": line}
...
>>> shards = [f"data{i}.txt" for i in range(32)]
>>> ds = IterableDataset.from_generator(gen, gen_kwargs={"shards": shards})
>>> ds = ds.shuffle(seed=42, buffer_size=10_000)  # shuffles the shards order + uses a shuffle buffer
>>> from torch.utils.data import DataLoader
>>> dataloader = DataLoader(ds.with_format("torch"), num_workers=4)  # give each worker a subset of 32/4=8 shards
```

**remove\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L1990)

( column\_names: typing.Union\[str, typing.List\[str]] ) → `IterableDataset`

Parameters

* **column\_names** (`Union[str, List[str]]`) — Name of the column(s) to remove.

Returns

`IterableDataset`

A copy of the dataset object without the columns to remove.

Remove one or several column(s) in the dataset and the features associated to them. The removal is done on-the-fly on the examples when iterating over the dataset.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True)
>>> next(iter(ds))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .', 'label': 1}
>>> ds = ds.remove_columns("label")
>>> next(iter(ds))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}
```

**select\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L2030)

( column\_names: typing.Union\[str, typing.List\[str]] ) → `IterableDataset`

Parameters

* **column\_names** (`Union[str, List[str]]`) — Name of the column(s) to select.

Returns

`IterableDataset`

A copy of the dataset object with selected columns.

Select one or several column(s) in the dataset and the features associated to them. The selection is done on-the-fly on the examples when iterating over the dataset.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True)
>>> next(iter(ds))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .', 'label': 1}
>>> ds = ds.select_columns("text")
>>> next(iter(ds))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}
```

**cast\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L2086)

( column: strfeature: typing.Union\[dict, list, tuple, datasets.features.features.Value, datasets.features.features.ClassLabel, datasets.features.translation.Translation, datasets.features.translation.TranslationVariableLanguages, datasets.features.features.Sequence, datasets.features.features.Array2D, datasets.features.features.Array3D, datasets.features.features.Array4D, datasets.features.features.Array5D, datasets.features.audio.Audio, datasets.features.image.Image] ) → `IterableDataset`

Parameters

* **column** (`str`) — Column name.
* **feature** (`Feature`) — Target feature.

Returns

`IterableDataset`

Cast column to feature for decoding.

Example:

Copied

```
>>> from datasets import load_dataset, Audio
>>> ds = load_dataset("PolyAI/minds14", name="en-US", split="train", streaming=True)
>>> ds.features
{'audio': Audio(sampling_rate=8000, mono=True, decode=True, id=None),
 'english_transcription': Value(dtype='string', id=None),
 'intent_class': ClassLabel(num_classes=14, names=['abroad', 'address', 'app_error', 'atm_limit', 'balance', 'business_loan',  'card_issues', 'cash_deposit', 'direct_debit', 'freeze', 'high_value_payment', 'joint_account', 'latest_transactions', 'pay_bill'], id=None),
 'lang_id': ClassLabel(num_classes=14, names=['cs-CZ', 'de-DE', 'en-AU', 'en-GB', 'en-US', 'es-ES', 'fr-FR', 'it-IT', 'ko-KR',  'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'zh-CN'], id=None),
 'path': Value(dtype='string', id=None),
 'transcription': Value(dtype='string', id=None)}
>>> ds = ds.cast_column("audio", Audio(sampling_rate=16000))
>>> ds.features
{'audio': Audio(sampling_rate=16000, mono=True, decode=True, id=None),
 'english_transcription': Value(dtype='string', id=None),
 'intent_class': ClassLabel(num_classes=14, names=['abroad', 'address', 'app_error', 'atm_limit', 'balance', 'business_loan',  'card_issues', 'cash_deposit', 'direct_debit', 'freeze', 'high_value_payment', 'joint_account', 'latest_transactions', 'pay_bill'], id=None),
 'lang_id': ClassLabel(num_classes=14, names=['cs-CZ', 'de-DE', 'en-AU', 'en-GB', 'en-US', 'es-ES', 'fr-FR', 'it-IT', 'ko-KR',  'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'zh-CN'], id=None),
 'path': Value(dtype='string', id=None),
 'transcription': Value(dtype='string', id=None)}
```

**cast**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L2137)

( features: Features ) → `IterableDataset`

Parameters

* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features)) — New features to cast the dataset to. The name of the fields in the features must match the current column names. The type of the data must also be convertible from one type to the other. For non-trivial conversion, e.g. `string` <-> `ClassLabel` you should use [map()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.map) to update the Dataset.

Returns

`IterableDataset`

A copy of the dataset with casted features.

Cast the dataset to a new set of features.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True)
>>> ds.features
{'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None),
 'text': Value(dtype='string', id=None)}
>>> new_features = ds.features.copy()
>>> new_features["label"] = ClassLabel(names=["bad", "good"])
>>> new_features["text"] = Value("large_string")
>>> ds = ds.cast(new_features)
>>> ds.features
{'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None),
 'text': Value(dtype='large_string', id=None)}
```

**\_\_iter\_\_**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L1351)

( )

**iter**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L1388)

( batch\_size: intdrop\_last\_batch: bool = False )

Parameters

* **batch\_size** (`int`) — size of each batch to yield.
* **drop\_last\_batch** (`bool`, default *False*) — Whether a last batch smaller than the batch\_size should be dropped

Iterate through the batches of size *batch\_size*.

**map**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L1571)

( function: typing.Optional\[typing.Callable] = Nonewith\_indices: bool = Falseinput\_columns: typing.Union\[str, typing.List\[str], NoneType] = Nonebatched: bool = Falsebatch\_size: typing.Optional\[int] = 1000drop\_last\_batch: bool = Falseremove\_columns: typing.Union\[str, typing.List\[str], NoneType] = Nonefeatures: typing.Optional\[datasets.features.features.Features] = Nonefn\_kwargs: typing.Optional\[dict] = None )

Parameters

* **function** (`Callable`, *optional*, defaults to `None`) — Function applied on-the-fly on the examples when you iterate on the dataset. It must have one of the following signatures:

  * `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` and `with_indices=False`
  * `function(example: Dict[str, Any], idx: int) -> Dict[str, Any]` if `batched=False` and `with_indices=True`
  * `function(batch: Dict[str, List]) -> Dict[str, List]` if `batched=True` and `with_indices=False`
  * `function(batch: Dict[str, List], indices: List[int]) -> Dict[str, List]` if `batched=True` and `with_indices=True`

  For advanced usage, the function can also return a `pyarrow.Table`. Moreover if your function returns nothing (`None`), then `map` will run your function and return the dataset unchanged. If no function is provided, default to identity function: `lambda x: x`.
* **with\_indices** (`bool`, defaults to `False`) — Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx[, rank]): ...`.
* **input\_columns** (`Optional[Union[str, List[str]]]`, defaults to `None`) — The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument.
* **batched** (`bool`, defaults to `False`) — Provide batch of examples to `function`.
* **batch\_size** (`int`, *optional*, defaults to `1000`) — Number of examples per batch provided to `function` if `batched=True`. `batch_size <= 0` or `batch_size == None` then provide the full dataset as a single batch to `function`.
* **drop\_last\_batch** (`bool`, defaults to `False`) — Whether a last batch smaller than the batch\_size should be dropped instead of being processed by the function.
* **remove\_columns** (`[List[str]]`, *optional*, defaults to `None`) — Remove a selection of columns while doing the mapping. Columns will be removed before updating the examples with the output of `function`, i.e. if `function` is adding columns with names in `remove_columns`, these columns will be kept.
* **features** (`[Features]`, *optional*, defaults to `None`) — Feature types of the resulting dataset.
* **fn\_kwargs** (`Dict`, *optional*, default `None`) — Keyword arguments to be passed to `function`.

Apply a function to all the examples in the iterable dataset (individually or in batches) and update them. If your function returns a column that already exists, then it overwrites it. The function is applied on-the-fly on the examples when iterating over the dataset.

You can specify whether the function should be batched or not with the `batched` parameter:

* If batched is `False`, then the function takes 1 example in and should return 1 example. An example is a dictionary, e.g. `{"text": "Hello there !"}`.
* If batched is `True` and `batch_size` is 1, then the function takes a batch of 1 example as input and can return a batch with 1 or more examples. A batch is a dictionary, e.g. a batch of 1 example is {“text”: \[“Hello there !”]}.
* If batched is `True` and `batch_size` is `n` > 1, then the function takes a batch of `n` examples as input and can return a batch with `n` examples, or with an arbitrary number of examples. Note that the last batch may have less than `n` examples. A batch is a dictionary, e.g. a batch of `n` examples is `{"text": ["Hello there !"] * n}`.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True)
>>> def add_prefix(example):
...     example["text"] = "Review: " + example["text"]
...     return example
>>> ds = ds.map(add_prefix)
>>> list(ds.take(3))
[{'label': 1,
 'text': 'Review: the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'Review: the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'Review: effective but too-tepid biopic'}]
```

**rename\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L1930)

( original\_column\_name: strnew\_column\_name: str ) → `IterableDataset`

Parameters

* **original\_column\_name** (`str`) — Name of the column to rename.
* **new\_column\_name** (`str`) — New name for the column.

Returns

`IterableDataset`

A copy of the dataset with a renamed column.

Rename a column in the dataset, and move the features associated to the original column under the new column name.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True)
>>> next(iter(ds))
{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}
>>> ds = ds.rename_column("text", "movie_review")
>>> next(iter(ds))
{'label': 1,
 'movie_review': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}
```

**filter**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L1684)

( function: typing.Optional\[typing.Callable] = Nonewith\_indices = Falseinput\_columns: typing.Union\[str, typing.List\[str], NoneType] = Nonebatched: bool = Falsebatch\_size: typing.Optional\[int] = 1000fn\_kwargs: typing.Optional\[dict] = None )

Parameters

* **function** (`Callable`) — Callable with one of the following signatures:

  * `function(example: Dict[str, Any]) -> bool` if `with_indices=False, batched=False`
  * `function(example: Dict[str, Any], indices: int) -> bool` if `with_indices=True, batched=False`
  * `function(example: Dict[str, List]) -> List[bool]` if `with_indices=False, batched=True`
  * `function(example: Dict[str, List], indices: List[int]) -> List[bool]` if `with_indices=True, batched=True`

  If no function is provided, defaults to an always True function: `lambda x: True`.
* **with\_indices** (`bool`, defaults to `False`) — Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`.
* **input\_columns** (`str` or `List[str]`, *optional*) — The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument.
* **batched** (`bool`, defaults to `False`) — Provide batch of examples to `function`.
* **batch\_size** (`int`, *optional*, default `1000`) — Number of examples per batch provided to `function` if `batched=True`.
* **fn\_kwargs** (`Dict`, *optional*, default `None`) — Keyword arguments to be passed to `function`.

Apply a filter function to all the elements so that the dataset only includes examples according to the filter function. The filtering is done on-the-fly when iterating over the dataset.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True)
>>> ds = ds.filter(lambda x: x["label"] == 0)
>>> list(ds.take(3))
[{'label': 0, 'movie_review': 'simplistic , silly and tedious .'},
 {'label': 0,
 'movie_review': "it's so laddish and juvenile , only teenage boys could possibly find it funny ."},
 {'label': 0,
 'movie_review': 'exploitative and largely devoid of the depth or sophistication that would make watching such a graphic treatment of the crimes bearable .'}]
```

**shuffle**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L1762)

( seed = Nonegenerator: typing.Optional\[numpy.random.\_generator.Generator] = Nonebuffer\_size: int = 1000 )

Parameters

* **seed** (`int`, *optional*, defaults to `None`) — Random seed that will be used to shuffle the dataset. It is used to sample from the shuffle buffe and also to shuffle the data shards.
* **generator** (`numpy.random.Generator`, *optional*) — Numpy random Generator to use to compute the permutation of the dataset rows. If `generator=None` (default), uses `np.random.default_rng` (the default BitGenerator (PCG64) of NumPy).
* **buffer\_size** (`int`, defaults to `1000`) — Size of the buffer.

Randomly shuffles the elements of this dataset.

This dataset fills a buffer with `buffer_size` elements, then randomly samples elements from this buffer, replacing the selected elements with new elements. For perfect shuffling, a buffer size greater than or equal to the full size of the dataset is required.

For instance, if your dataset contains 10,000 elements but `buffer_size` is set to 1000, then `shuffle` will initially select a random element from only the first 1000 elements in the buffer. Once an element is selected, its space in the buffer is replaced by the next (i.e. 1,001-st) element, maintaining the 1000 element buffer.

If the dataset is made of several shards, it also does shuffle the order of the shards. However if the order has been fixed by using [skip()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset.skip) or [take()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset.take) then the order of the shards is kept unchanged.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True)
>>> list(ds.take(3))
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'}]
>>> shuffled_ds = ds.shuffle(seed=42)
>>> list(shuffled_ds.take(3))
[{'label': 1,
 'text': "a sports movie with action that's exciting on the field and a story you care about off it ."},
 {'label': 1,
 'text': 'at its best , the good girl is a refreshingly adult take on adultery . . .'},
 {'label': 1,
 'text': "sam jones became a very lucky filmmaker the day wilco got dropped from their record label , proving that one man's ruin may be another's fortune ."}]
```

**skip**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L1832)

( n )

Parameters

* **n** (`int`) — Number of elements to skip.

Create a new [IterableDataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset) that skips the first `n` elements.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True)
>>> list(ds.take(3))
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'}]
>>> ds = ds.skip(1)
>>> list(ds.take(3))
[{'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'},
 {'label': 1,
 'text': 'if you sometimes like to go to the movies to have fun , wasabi is a good place to start .'}]
```

**take**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/iterable_dataset.py#L1871)

( n )

Parameters

* **n** (`int`) — Number of elements to take.

Create a new [IterableDataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset) with only the first `n` elements.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True)
>>> small_ds = ds.take(2)
>>> list(small_ds)
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'}]
```

**info**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L158)

( )

[DatasetInfo](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.DatasetInfo) object containing all the metadata in the dataset.

**split**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L163)

( )

[NamedSplit](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.NamedSplit) object corresponding to a named dataset split.

**builder\_name**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L168)

( )

**citation**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L172)

( )

**config\_name**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L176)

( )

**dataset\_size**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L180)

( )

**description**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L184)

( )

**download\_checksums**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L188)

( )

**download\_size**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L192)

( )

**features**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L196)

( )

**homepage**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L200)

( )

**license**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L204)

( )

**size\_in\_bytes**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L208)

( )

**supervised\_keys**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L212)

( )

**version**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_dataset.py#L220)

( )

### IterableDatasetDict

Dictionary with split names as keys (‘train’, ‘test’ for example), and `IterableDataset` objects as values.

#### class datasets.IterableDatasetDict

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1755)

( )

**map**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1785)

( function: typing.Optional\[typing.Callable] = Nonewith\_indices: bool = Falseinput\_columns: typing.Union\[str, typing.List\[str], NoneType] = Nonebatched: bool = Falsebatch\_size: int = 1000drop\_last\_batch: bool = Falseremove\_columns: typing.Union\[str, typing.List\[str], NoneType] = Nonefn\_kwargs: typing.Optional\[dict] = None )

Parameters

* **function** (`Callable`, *optional*, defaults to `None`) — Function applied on-the-fly on the examples when you iterate on the dataset. It must have one of the following signatures:

  * `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` and `with_indices=False`
  * `function(example: Dict[str, Any], idx: int) -> Dict[str, Any]` if `batched=False` and `with_indices=True`
  * `function(batch: Dict[str, List]) -> Dict[str, List]` if `batched=True` and `with_indices=False`
  * `function(batch: Dict[str, List], indices: List[int]) -> Dict[str, List]` if `batched=True` and `with_indices=True`

  For advanced usage, the function can also return a `pyarrow.Table`. Moreover if your function returns nothing (`None`), then `map` will run your function and return the dataset unchanged. If no function is provided, default to identity function: `lambda x: x`.
* **with\_indices** (`bool`, defaults to `False`) — Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx[, rank]): ...`.
* **input\_columns** (`[Union[str, List[str]]]`, *optional*, defaults to `None`) — The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument.
* **batched** (`bool`, defaults to `False`) — Provide batch of examples to `function`.
* **batch\_size** (`int`, *optional*, defaults to `1000`) — Number of examples per batch provided to `function` if `batched=True`.
* **drop\_last\_batch** (`bool`, defaults to `False`) — Whether a last batch smaller than the `batch_size` should be dropped instead of being processed by the function.
* **remove\_columns** (`[List[str]]`, *optional*, defaults to `None`) — Remove a selection of columns while doing the mapping. Columns will be removed before updating the examples with the output of `function`, i.e. if `function` is adding columns with names in `remove_columns`, these columns will be kept.
* **fn\_kwargs** (`Dict`, *optional*, defaults to `None`) — Keyword arguments to be passed to `function`

Apply a function to all the examples in the iterable dataset (individually or in batches) and update them. If your function returns a column that already exists, then it overwrites it. The function is applied on-the-fly on the examples when iterating over the dataset. The transformation is applied to all the datasets of the dataset dictionary.

You can specify whether the function should be batched or not with the `batched` parameter:

* If batched is `False`, then the function takes 1 example in and should return 1 example. An example is a dictionary, e.g. `{"text": "Hello there !"}`.
* If batched is `True` and `batch_size` is 1, then the function takes a batch of 1 example as input and can return a batch with 1 or more examples. A batch is a dictionary, e.g. a batch of 1 example is `{"text": ["Hello there !"]}`.
* If batched is `True` and `batch_size` is `n` > 1, then the function takes a batch of `n` examples as input and can return a batch with `n` examples, or with an arbitrary number of examples. Note that the last batch may have less than `n` examples. A batch is a dictionary, e.g. a batch of `n` examples is `{"text": ["Hello there !"] * n}`.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> def add_prefix(example):
...     example["text"] = "Review: " + example["text"]
...     return example
>>> ds = ds.map(add_prefix)
>>> next(iter(ds["train"]))
{'label': 1,
 'text': 'Review: the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}
```

**filter**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1874)

( function: typing.Optional\[typing.Callable] = Nonewith\_indices = Falseinput\_columns: typing.Union\[str, typing.List\[str], NoneType] = Nonebatched: bool = Falsebatch\_size: typing.Optional\[int] = 1000fn\_kwargs: typing.Optional\[dict] = None )

Parameters

* **function** (`Callable`) — Callable with one of the following signatures:

  * `function(example: Dict[str, Any]) -> bool` if `with_indices=False, batched=False`
  * `function(example: Dict[str, Any], indices: int) -> bool` if `with_indices=True, batched=False`
  * `function(example: Dict[str, List]) -> List[bool]` if `with_indices=False, batched=True`
  * `function(example: Dict[str, List], indices: List[int]) -> List[bool]` if `with_indices=True, batched=True`

  If no function is provided, defaults to an always True function: `lambda x: True`.
* **with\_indices** (`bool`, defaults to `False`) — Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`.
* **input\_columns** (`str` or `List[str]`, *optional*) — The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument.
* **batched** (`bool`, defaults to `False`) — Provide batch of examples to `function`
* **batch\_size** (`int`, *optional*, defaults to `1000`) — Number of examples per batch provided to `function` if `batched=True`.
* **fn\_kwargs** (`Dict`, *optional*, defaults to `None`) — Keyword arguments to be passed to `function`

Apply a filter function to all the elements so that the dataset only includes examples according to the filter function. The filtering is done on-the-fly when iterating over the dataset. The filtering is applied to all the datasets of the dataset dictionary.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds = ds.filter(lambda x: x["label"] == 0)
>>> list(ds["train"].take(3))
[{'label': 0, 'text': 'Review: simplistic , silly and tedious .'},
 {'label': 0,
 'text': "Review: it's so laddish and juvenile , only teenage boys could possibly find it funny ."},
 {'label': 0,
 'text': 'Review: exploitative and largely devoid of the depth or sophistication that would make watching such a graphic treatment of the crimes bearable .'}]
```

**shuffle**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1937)

( seed = Nonegenerator: typing.Optional\[numpy.random.\_generator.Generator] = Nonebuffer\_size: int = 1000 )

Parameters

* **seed** (`int`, *optional*, defaults to `None`) — Random seed that will be used to shuffle the dataset. It is used to sample from the shuffle buffe and als oto shuffle the data shards.
* **generator** (`numpy.random.Generator`, *optional*) — Numpy random Generator to use to compute the permutation of the dataset rows. If `generator=None` (default), uses `np.random.default_rng` (the default BitGenerator (PCG64) of NumPy).
* **buffer\_size** (`int`, defaults to `1000`) — Size of the buffer.

Randomly shuffles the elements of this dataset. The shuffling is applied to all the datasets of the dataset dictionary.

This dataset fills a buffer with buffer\_size elements, then randomly samples elements from this buffer, replacing the selected elements with new elements. For perfect shuffling, a buffer size greater than or equal to the full size of the dataset is required.

For instance, if your dataset contains 10,000 elements but `buffer_size` is set to 1000, then `shuffle` will initially select a random element from only the first 1000 elements in the buffer. Once an element is selected, its space in the buffer is replaced by the next (i.e. 1,001-st) element, maintaining the 1000 element buffer.

If the dataset is made of several shards, it also does `shuffle` the order of the shards. However if the order has been fixed by using [skip()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset.skip) or [take()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDataset.take) then the order of the shards is kept unchanged.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> list(ds["train"].take(3))
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .'},
 {'label': 1, 'text': 'effective but too-tepid biopic'}]
>>> ds = ds.shuffle(seed=42)
>>> list(ds["train"].take(3))
[{'label': 1,
 'text': "a sports movie with action that's exciting on the field and a story you care about off it ."},
 {'label': 1,
 'text': 'at its best , the good girl is a refreshingly adult take on adultery . . .'},
 {'label': 1,
 'text': "sam jones became a very lucky filmmaker the day wilco got dropped from their record label , proving that one man's ruin may be another's fortune ."}]
```

**with\_format**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1756)

( type: typing.Optional\[str] = None )

Parameters

* **type** (`str`, *optional*, defaults to `None`) — If set to “torch”, the returned dataset will be a subclass of `torch.utils.data.IterableDataset` to be used in a `DataLoader`.

Return a dataset with the specified format. This method only supports the “torch” format for now. The format is set to all the datasets of the dataset dictionary.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> from transformers import AutoTokenizer
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
>>> def encode(example):
...     return tokenizer(examples["text"], truncation=True, padding="max_length")
>>> ds = ds.map(encode, batched=True, remove_columns=["text"])
>>> ds = ds.with_format("torch")
```

**cast**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L2139)

( features: Features ) → [IterableDatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDatasetDict)

Parameters

* **features** (`Features`) — New features to cast the dataset to. The name of the fields in the features must match the current column names. The type of the data must also be convertible from one type to the other. For non-trivial conversion, e.g. `string` <-> `ClassLabel` you should use `map` to update the Dataset.

Returns

[IterableDatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDatasetDict)

A copy of the dataset with casted features.

Cast the dataset to a new set of features. The type casting is applied to all the datasets of the dataset dictionary.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds["train"].features
{'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None),
 'text': Value(dtype='string', id=None)}
>>> new_features = ds["train"].features.copy()
>>> new_features['label'] = ClassLabel(names=['bad', 'good'])
>>> new_features['text'] = Value('large_string')
>>> ds = ds.cast(new_features)
>>> ds["train"].features
{'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None),
 'text': Value(dtype='large_string', id=None)}
```

**cast\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L2108)

( column: strfeature: typing.Union\[dict, list, tuple, datasets.features.features.Value, datasets.features.features.ClassLabel, datasets.features.translation.Translation, datasets.features.translation.TranslationVariableLanguages, datasets.features.features.Sequence, datasets.features.features.Array2D, datasets.features.features.Array3D, datasets.features.features.Array4D, datasets.features.features.Array5D, datasets.features.audio.Audio, datasets.features.image.Image] )

Parameters

* **column** (`str`) — Column name.
* **feature** (`Feature`) — Target feature.

Cast column to feature for decoding. The type casting is applied to all the datasets of the dataset dictionary.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds["train"].features
{'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None),
 'text': Value(dtype='string', id=None)}
>>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good']))
>>> ds["train"].features
{'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None),
 'text': Value(dtype='string', id=None)}
```

**remove\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L2056)

( column\_names: typing.Union\[str, typing.List\[str]] ) → [IterableDatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDatasetDict)

Parameters

* **column\_names** (`Union[str, List[str]]`) — Name of the column(s) to remove.

Returns

[IterableDatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDatasetDict)

A copy of the dataset object without the columns to remove.

Remove one or several column(s) in the dataset and the features associated to them. The removal is done on-the-fly on the examples when iterating over the dataset. The removal is applied to all the datasets of the dataset dictionary.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds = ds.remove_columns("label")
>>> next(iter(ds["train"]))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}
```

**rename\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L1995)

( original\_column\_name: strnew\_column\_name: str ) → [IterableDatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDatasetDict)

Parameters

* **original\_column\_name** (`str`) — Name of the column to rename.
* **new\_column\_name** (`str`) — New name for the column.

Returns

[IterableDatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDatasetDict)

A copy of the dataset with a renamed column.

Rename a column in the dataset, and move the features associated to the original column under the new column name. The renaming is applied to all the datasets of the dataset dictionary.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds = ds.rename_column("text", "movie_review")
>>> next(iter(ds["train"]))
{'label': 1,
 'movie_review': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}
```

**rename\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L2028)

( column\_mapping: typing.Dict\[str, str] ) → [IterableDatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDatasetDict)

Parameters

* **column\_mapping** (`Dict[str, str]`) — A mapping of columns to rename to their new names.

Returns

[IterableDatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDatasetDict)

A copy of the dataset with renamed columns

Rename several columns in the dataset, and move the features associated to the original columns under the new column names. The renaming is applied to all the datasets of the dataset dictionary.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds = ds.rename_columns({"text": "movie_review", "label": "rating"})
>>> next(iter(ds["train"]))
{'movie_review': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .',
 'rating': 1}
```

**select\_columns**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/dataset_dict.py#L2082)

( column\_names: typing.Union\[str, typing.List\[str]] ) → [IterableDatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDatasetDict)

Parameters

* **column\_names** (`Union[str, List[str]]`) — Name of the column(s) to keep.

Returns

[IterableDatasetDict](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.IterableDatasetDict)

A copy of the dataset object with only selected columns.

Select one or several column(s) in the dataset and the features associated to them. The selection is done on-the-fly on the examples when iterating over the dataset. The selection is applied to all the datasets of the dataset dictionary.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds = ds.select("text")
>>> next(iter(ds["train"]))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}
```

### Features

#### class datasets.Features

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1567)

( \*args\*\*kwargs )

A special dictionary that defines the internal structure of a dataset.

Instantiated with a dictionary of type `dict[str, FieldType]`, where keys are the desired column names, and values are the type of that column.

`FieldType` can be one of the following:

* a [Value](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Value) feature specifies a single typed value, e.g. `int64` or `string`.
* a [ClassLabel](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.ClassLabel) feature specifies a field with a predefined set of classes which can have labels associated to them and will be stored as integers in the dataset.
* a python `dict` which specifies that the field is a nested field containing a mapping of sub-fields to sub-fields features. It’s possible to have nested fields of nested fields in an arbitrary manner.
* a python `list` or a [Sequence](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Sequence) specifies that the field contains a list of objects. The python `list` or [Sequence](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Sequence) should be provided with a single sub-feature as an example of the feature type hosted in this list.

  A [Sequence](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Sequence) with a internal dictionary feature will be automatically converted into a dictionary of lists. This behavior is implemented to have a compatilbity layer with the TensorFlow Datasets library but may be un-wanted in some cases. If you don’t want this behavior, you can use a python `list` instead of the [Sequence](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Sequence).
* a [Array2D](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Array2D), [Array3D](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Array3D), [Array4D](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Array4D) or [Array5D](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Array5D) feature for multidimensional arrays.
* an [Audio](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Audio) feature to store the absolute path to an audio file or a dictionary with the relative path to an audio file (“path” key) and its bytes content (“bytes” key). This feature extracts the audio data.
* an [Image](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Image) feature to store the absolute path to an image file, an `np.ndarray` object, a `PIL.Image.Image` object or a dictionary with the relative path to an image file (“path” key) and its bytes content (“bytes” key). This feature extracts the image data.
* [Translation](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Translation) and [TranslationVariableLanguages](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.TranslationVariableLanguages), the two features specific to Machine Translation.

**copy**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1957)

( )

Make a deep copy of [Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features).

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train")
>>> copy_of_features = ds.features.copy()
>>> copy_of_features
{'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None),
 'text': Value(dtype='string', id=None)}
```

**decode\_batch**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1930)

( batch: dicttoken\_per\_repo\_id: typing.Union\[typing.Dict\[str, typing.Union\[str, bool, NoneType]], NoneType] = None )

Parameters

* **batch** (`dict[str, list[Any]]`) — Dataset batch data.
* **token\_per\_repo\_id** (`dict`, *optional*) — To access and decode audio or image files from private repositories on the Hub, you can pass a dictionary repo\_id (str) -> token (bool or str)

Decode batch with custom feature decoding.

**decode\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1912)

( column: listcolumn\_name: str )

Parameters

* **column** (`list[Any]`) — Dataset column data.
* **column\_name** (`str`) — Dataset column name.

Decode column with custom feature decoding.

**decode\_example**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1889)

( example: dicttoken\_per\_repo\_id: typing.Union\[typing.Dict\[str, typing.Union\[str, bool, NoneType]], NoneType] = None )

Parameters

* **example** (`dict[str, Any]`) — Dataset row data.
* **token\_per\_repo\_id** (`dict`, *optional*) — To access and decode audio or image files from private repositories on the Hub, you can pass a dictionary `repo_id (str) -> token (bool or str)`.

Decode example with custom feature decoding.

**encode\_batch**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1870)

( batch )

Parameters

* **batch** (`dict[str, list[Any]]`) — Data in a Dataset batch.

Encode batch into a format for Arrow.

**encode\_column**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1854)

( columncolumn\_name: str )

Parameters

* **column** (`list[Any]`) — Data in a Dataset column.
* **column\_name** (`str`) — Dataset column name.

Encode column into a format for Arrow.

**encode\_example**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1840)

( example )

Parameters

* **example** (`dict[str, Any]`) — Data in a Dataset row.

Encode example into a format for Arrow.

**flatten**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L2044)

( max\_depth = 16 ) → [Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features)

Returns

[Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features)

The flattened features.

Flatten the features. Every dictionary column is removed and is replaced by all the subfields it contains. The new fields are named by concatenating the name of the original column and the subfield name like this: `<original>.<subfield>`.

If a column contains nested dictionaries, then all the lower-level subfields names are also concatenated to form new columns: `<original>.<subfield>.<subsubfield>`, etc.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("squad", split="train")
>>> ds.features.flatten()
{'answers.answer_start': Sequence(feature=Value(dtype='int32', id=None), length=-1, id=None),
 'answers.text': Sequence(feature=Value(dtype='string', id=None), length=-1, id=None),
 'context': Value(dtype='string', id=None),
 'id': Value(dtype='string', id=None),
 'question': Value(dtype='string', id=None),
 'title': Value(dtype='string', id=None)}
```

**from\_arrow\_schema**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1642)

( pa\_schema: Schema )

Parameters

* **pa\_schema** (`pyarrow.Schema`) — Arrow Schema.

Construct [Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features) from Arrow Schema. It also checks the schema metadata for BOINC AI Datasets features. Non-nullable fields are not supported and set to nullable.

**from\_dict**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1664)

( dic ) → *Features*

Parameters

* **dic** (*dict\[str, Any]*) — Python dictionary.

Returns

*Features*

Construct \[*Features*] from dict.

Regenerate the nested feature object from a deserialized dict. We use the *\_type* key to infer the dataclass name of the feature *FieldType*.

It allows for a convenient constructor syntax to define features from deserialized JSON dictionaries. This function is used in particular when deserializing a \[*DatasetInfo*] that was dumped to a JSON object. This acts as an analogue to \[*Features.from\_arrow\_schema*] and handles the recursive field-by-field instantiation, but doesn’t require any mapping to/from pyarrow, except for the fact that it takes advantage of the mapping of pyarrow primitive dtypes that \[*Value*] automatically performs.

Example:

Copied

```
>>> Features.from_dict({'_type': {'dtype': 'string', 'id': None, '_type': 'Value'}})
{'_type': Value(dtype='string', id=None)}
```

**reorder\_fields\_as**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1977)

( other: Features )

Parameters

* **other** (\[*Features*]) — The other \[*Features*] to align with.

Reorder Features fields to match the field order of other \[*Features*].

The order of the fields is important since it matters for the underlying arrow data. Re-ordering the fields allows to make the underlying arrow data type match.

Example:

Copied

```
>>> from datasets import Features, Sequence, Value
>>> # let's say we have to features with a different order of nested fields (for a and b for example)
>>> f1 = Features({"root": Sequence({"a": Value("string"), "b": Value("string")})})
>>> f2 = Features({"root": {"b": Sequence(Value("string")), "a": Sequence(Value("string"))}})
>>> assert f1.type != f2.type
>>> # re-ordering keeps the base structure (here Sequence is defined at the root level), but make the fields order match
>>> f1.reorder_fields_as(f2)
{'root': Sequence(feature={'b': Value(dtype='string', id=None), 'a': Value(dtype='string', id=None)}, length=-1, id=None)}
>>> assert f1.reorder_fields_as(f2).type == f2.type
```

#### class datasets.Sequence

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1115)

( feature: typing.Anylength: int = -1id: typing.Optional\[str] = None )

Parameters

* **length** (`int`) — Length of the sequence.

Construct a list of feature from a single type or a dict of types. Mostly here for compatiblity with tfds.

Example:

Copied

```
>>> from datasets import Features, Sequence, Value, ClassLabel
>>> features = Features({'post': Sequence(feature={'text': Value(dtype='string'), 'upvotes': Value(dtype='int32'), 'label': ClassLabel(num_classes=2, names=['hot', 'cold'])})})
>>> features
{'post': Sequence(feature={'text': Value(dtype='string', id=None), 'upvotes': Value(dtype='int32', id=None), 'label': ClassLabel(num_classes=2, names=['hot', 'cold'], id=None)}, length=-1, id=None)}
```

#### class datasets.ClassLabel

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L917)

( num\_classes: dataclasses.InitVar\[typing.Optional\[int]] = Nonenames: typing.List\[str] = Nonenames\_file: dataclasses.InitVar\[typing.Optional\[str]] = Noneid: typing.Optional\[str] = None )

Parameters

* **num\_classes** (`int`, *optional*) — Number of classes. All labels must be < `num_classes`.
* **names** (`list` of `str`, *optional*) — String names for the integer classes. The order in which the names are provided is kept.
* **names\_file** (`str`, *optional*) — Path to a file with names for the integer classes, one per line.

Feature type for integer class labels.

There are 3 ways to define a `ClassLabel`, which correspond to the 3 arguments:

* `num_classes`: Create 0 to (num\_classes-1) labels.
* `names`: List of label strings.
* `names_file`: File containing the list of labels.

Under the hood the labels are stored as integers. You can use negative integers to represent unknown/missing labels.

Example:

Copied

```
>>> from datasets import Features
>>> features = Features({'label': ClassLabel(num_classes=3, names=['bad', 'ok', 'good'])})
>>> features
{'label': ClassLabel(num_classes=3, names=['bad', 'ok', 'good'], id=None)}
```

**cast\_storage**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1082)

( storage: typing.Union\[pyarrow\.lib.StringArray, pyarrow\.lib.IntegerArray] ) → `pa.Int64Array`

Parameters

* **storage** (`Union[pa.StringArray, pa.IntegerArray]`) — PyArrow array to cast.

Returns

`pa.Int64Array`

Array in the `ClassLabel` arrow storage type.

Cast an Arrow array to the `ClassLabel` arrow storage type. The Arrow types that can be converted to the `ClassLabel` pyarrow storage type are:

* `pa.string()`
* `pa.int()`

**int2str**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L1036)

( values: typing.Union\[int, collections.abc.Iterable] )

Conversion `integer` => class name `string`.

Regarding unknown/missing labels: passing negative integers raises `ValueError`.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train")
>>> ds.features["label"].int2str(0)
'neg'
```

**str2int**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L991)

( values: typing.Union\[str, collections.abc.Iterable] )

Conversion class name `string` => `integer`.

Example:

Copied

```
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train")
>>> ds.features["label"].str2int('neg')
0
```

#### class datasets.Value

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L452)

( dtype: strid: typing.Optional\[str] = None )

The `Value` dtypes are as follows:

* `null`
* `bool`
* `int8`
* `int16`
* `int32`
* `int64`
* `uint8`
* `uint16`
* `uint32`
* `uint64`
* `float16`
* `float32` (alias float)
* `float64` (alias double)
* `time32[(s|ms)]`
* `time64[(us|ns)]`
* `timestamp[(s|ms|us|ns)]`
* `timestamp[(s|ms|us|ns), tz=(tzstring)]`
* `date32`
* `date64`
* `duration[(s|ms|us|ns)]`
* `decimal128(precision, scale)`
* `decimal256(precision, scale)`
* `binary`
* `large_binary`
* `string`
* `large_string`

Example:

Copied

```
>>> from datasets import Features
>>> features = Features({'stars': Value(dtype='int32')})
>>> features
{'stars': Value(dtype='int32', id=None)}
```

#### class datasets.Translation

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/translation.py#L12)

( languages: typing.List\[str]id: typing.Optional\[str] = None )

Parameters

* **languages** (`dict`) — A dictionary for each example mapping string language codes to string translations.

`FeatureConnector` for translations with fixed languages per example. Here for compatiblity with tfds.

Example:

Copied

```
>>> # At construction time:
>>> datasets.features.Translation(languages=['en', 'fr', 'de'])
>>> # During data generation:
>>> yield {
...         'en': 'the cat',
...         'fr': 'le chat',
...         'de': 'die katze'
... }
```

**flatten**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/translation.py#L44)

( )

Flatten the Translation feature into a dictionary.

#### class datasets.TranslationVariableLanguages

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/translation.py#L52)

( languages: typing.Optional\[typing.List] = Nonenum\_languages: typing.Optional\[int] = Noneid: typing.Optional\[str] = None ) →

* `language` or `translation` (variable-length 1D `tf.Tensor` of `tf.string`)

Parameters

* **languages** (`dict`) — A dictionary for each example mapping string language codes to one or more string translations. The languages present may vary from example to example.

Returns

* `language` or `translation` (variable-length 1D `tf.Tensor` of `tf.string`)

Language codes sorted in ascending order or plain text translations, sorted to align with language codes.

`FeatureConnector` for translations with variable languages per example. Here for compatiblity with tfds.

Example:

Copied

```
>>> # At construction time:
>>> datasets.features.TranslationVariableLanguages(languages=['en', 'fr', 'de'])
>>> # During data generation:
>>> yield {
...         'en': 'the cat',
...         'fr': ['le chat', 'la chatte,']
...         'de': 'die katze'
... }
>>> # Tensor returned :
>>> {
...         'language': ['en', 'de', 'fr', 'fr'],
...         'translation': ['the cat', 'die katze', 'la chatte', 'le chat'],
... }
```

**flatten**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/translation.py#L120)

( )

Flatten the TranslationVariableLanguages feature into a dictionary.

#### class datasets.Array2D

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L535)

( shape: tupledtype: strid: typing.Optional\[str] = None )

Parameters

* **shape** (`tuple`) — The size of each dimension.
* **dtype** (`str`) — The value of the data type.

Create a two-dimensional array.

Example:

Copied

```
>>> from datasets import Features
>>> features = Features({'x': Array2D(shape=(1, 3), dtype='int32')})
```

#### class datasets.Array3D

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L560)

( shape: tupledtype: strid: typing.Optional\[str] = None )

Parameters

* **shape** (`tuple`) — The size of each dimension.
* **dtype** (`str`) — The value of the data type.

Create a three-dimensional array.

Example:

Copied

```
>>> from datasets import Features
>>> features = Features({'x': Array3D(shape=(1, 2, 3), dtype='int32')})
```

#### class datasets.Array4D

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L585)

( shape: tupledtype: strid: typing.Optional\[str] = None )

Parameters

* **shape** (`tuple`) — The size of each dimension.
* **dtype** (`str`) — The value of the data type.

Create a four-dimensional array.

Example:

Copied

```
>>> from datasets import Features
>>> features = Features({'x': Array4D(shape=(1, 2, 2, 3), dtype='int32')})
```

#### class datasets.Array5D

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/features.py#L610)

( shape: tupledtype: strid: typing.Optional\[str] = None )

Parameters

* **shape** (`tuple`) — The size of each dimension.
* **dtype** (`str`) — The value of the data type.

Create a five-dimensional array.

Example:

Copied

```
>>> from datasets import Features
>>> features = Features({'x': Array5D(shape=(1, 2, 2, 3, 3), dtype='int32')})
```

#### class datasets.Audio

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/audio.py#L24)

( sampling\_rate: typing.Optional\[int] = Nonemono: bool = Truedecode: bool = Trueid: typing.Optional\[str] = None )

Parameters

* **sampling\_rate** (`int`, *optional*) — Target sampling rate. If `None`, the native sampling rate is used.
* **mono** (`bool`, defaults to `True`) — Whether to convert the audio signal to mono by averaging samples across channels.
* **decode** (`bool`, defaults to `True`) — Whether to decode the audio data. If `False`, returns the underlying dictionary in the format `{"path": audio_path, "bytes": audio_bytes}`.

Audio `Feature` to extract audio data from an audio file.

Input: The Audio feature accepts as input:

* A `str`: Absolute path to the audio file (i.e. random access is allowed).
* A `dict` with the keys:

  * `path`: String with relative path of the audio file to the archive file.
  * `bytes`: Bytes content of the audio file.

  This is useful for archived files with sequential access.
* A `dict` with the keys:

  * `path`: String with relative path of the audio file to the archive file.
  * `array`: Array containing the audio sample
  * `sampling_rate`: Integer corresponding to the sampling rate of the audio sample.

  This is useful for archived files with sequential access.

Example:

Copied

```
>>> from datasets import load_dataset, Audio
>>> ds = load_dataset("PolyAI/minds14", name="en-US", split="train")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=16000))
>>> ds[0]["audio"]
{'array': array([ 2.3443763e-05,  2.1729663e-04,  2.2145823e-04, ...,
     3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32),
 'path': '/root/.cache/boincai/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
 'sampling_rate': 16000}
```

**cast\_storage**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/audio.py#L212)

( storage: typing.Union\[pyarrow\.lib.StringArray, pyarrow\.lib.StructArray] ) → `pa.StructArray`

Parameters

* **storage** (`Union[pa.StringArray, pa.StructArray]`) — PyArrow array to cast.

Returns

`pa.StructArray`

Array in the Audio arrow storage type, that is `pa.struct({"bytes": pa.binary(), "path": pa.string()})`

Cast an Arrow array to the Audio arrow storage type. The Arrow types that can be converted to the Audio pyarrow storage type are:

* `pa.string()` - it must contain the “path” data
* `pa.binary()` - it must contain the audio bytes
* `pa.struct({"bytes": pa.binary()})`
* `pa.struct({"path": pa.string()})`
* `pa.struct({"bytes": pa.binary(), "path": pa.string()})` - order doesn’t matter

**decode\_example**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/audio.py#L129)

( value: dicttoken\_per\_repo\_id: typing.Union\[typing.Dict\[str, typing.Union\[str, bool, NoneType]], NoneType] = None ) → `dict`

Parameters

* **value** (`dict`) — A dictionary with keys:
  * `path`: String with relative audio file path.
  * `bytes`: Bytes of the audio file.
* **token\_per\_repo\_id** (`dict`, *optional*) — To access and decode audio files from private repositories on the Hub, you can pass a dictionary repo\_id (`str`) -> token (`bool` or `str`)

Returns

`dict`

Decode example audio file into audio data.

**embed\_storage**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/audio.py#L250)

( storage: StructArray ) → `pa.StructArray`

Parameters

* **storage** (`pa.StructArray`) — PyArrow array to embed.

Returns

`pa.StructArray`

Array in the Audio arrow storage type, that is `pa.struct({"bytes": pa.binary(), "path": pa.string()})`.

Embed audio files into the Arrow array.

**encode\_example**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/audio.py#L80)

( value: typing.Union\[str, bytes, dict] ) → `dict`

Parameters

* **value** (`str` or `dict`) — Data passed as input to Audio feature.

Returns

`dict`

Encode example into a format for Arrow.

**flatten**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/audio.py#L201)

( )

If in the decodable state, raise an error, otherwise flatten the feature into a dictionary.

#### class datasets.Image

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/image.py#L47)

( decode: bool = Trueid: typing.Optional\[str] = None )

Parameters

* **decode** (`bool`, defaults to `True`) — Whether to decode the image data. If `False`, returns the underlying dictionary in the format `{"path": image_path, "bytes": image_bytes}`.

Image `Feature` to read image data from an image file.

Input: The Image feature accepts as input:

* A `str`: Absolute path to the image file (i.e. random access is allowed).
* A `dict` with the keys:

  * `path`: String with relative path of the image file to the archive file.
  * `bytes`: Bytes of the image file.

  This is useful for archived files with sequential access.
* An `np.ndarray`: NumPy array representing an image.
* A `PIL.Image.Image`: PIL image object.

Examples:

Copied

```
>>> from datasets import load_dataset, Image
>>> ds = load_dataset("beans", split="train")
>>> ds.features["image"]
Image(decode=True, id=None)
>>> ds[0]["image"]
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=500x500 at 0x15E52E7F0>
>>> ds = ds.cast_column('image', Image(decode=False))
{'bytes': None,
 'path': '/root/.cache/boincai/datasets/downloads/extracted/b0a21163f78769a2cf11f58dfc767fb458fc7cea5c05dccc0144a2c0f0bc1292/train/healthy/healthy_train.85.jpg'}
```

**cast\_storage**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/image.py#L201)

( storage: typing.Union\[pyarrow\.lib.StringArray, pyarrow\.lib.StructArray, pyarrow\.lib.ListArray] ) → `pa.StructArray`

Parameters

* **storage** (`Union[pa.StringArray, pa.StructArray, pa.ListArray]`) — PyArrow array to cast.

Returns

`pa.StructArray`

Array in the Image arrow storage type, that is `pa.struct({"bytes": pa.binary(), "path": pa.string()})`.

Cast an Arrow array to the Image arrow storage type. The Arrow types that can be converted to the Image pyarrow storage type are:

* `pa.string()` - it must contain the “path” data
* `pa.binary()` - it must contain the image bytes
* `pa.struct({"bytes": pa.binary()})`
* `pa.struct({"path": pa.string()})`
* `pa.struct({"bytes": pa.binary(), "path": pa.string()})` - order doesn’t matter
* `pa.list(*)` - it must contain the image array data

**decode\_example**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/image.py#L131)

( value: dicttoken\_per\_repo\_id = None )

Parameters

* **value** (`str` or `dict`) — A string with the absolute image file path, a dictionary with keys:
  * `path`: String with absolute or relative image file path.
  * `bytes`: The bytes of the image file.
* **token\_per\_repo\_id** (`dict`, *optional*) — To access and decode image files from private repositories on the Hub, you can pass a dictionary repo\_id (`str`) -> token (`bool` or `str`).

Decode example image file into image data.

**embed\_storage**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/image.py#L247)

( storage: StructArray ) → `pa.StructArray`

Parameters

* **storage** (`pa.StructArray`) — PyArrow array to embed.

Returns

`pa.StructArray`

Array in the Image arrow storage type, that is `pa.struct({"bytes": pa.binary(), "path": pa.string()})`.

Embed image files into the Arrow array.

**encode\_example**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/image.py#L92)

( value: typing.Union\[str, bytes, dict, numpy.ndarray, ForwardRef('PIL.Image.Image')] )

Parameters

* **value** (`str`, `np.ndarray`, `PIL.Image.Image` or `dict`) — Data passed as input to Image feature.

Encode example into a format for Arrow.

**flatten**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/features/image.py#L188)

( )

If in the decodable state, return the feature itself, otherwise flatten the feature into a dictionary.

### MetricInfo

#### class datasets.MetricInfo

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/info.py#L516)

( description: strcitation: strfeatures: Featuresinputs\_description: str = \<factory>homepage: str = \<factory>license: str = \<factory>codebase\_urls: typing.List\[str] = \<factory>reference\_urls: typing.List\[str] = \<factory>streamable: bool = Falseformat: typing.Optional\[str] = Nonemetric\_name: typing.Optional\[str] = Noneconfig\_name: typing.Optional\[str] = Noneexperiment\_id: typing.Optional\[str] = None )

Information about a metric.

`MetricInfo` documents a metric, including its name, version, and features. See the constructor arguments and properties for a full list.

Note: Not all fields are known on construction and may be updated later.

**from\_directory**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/info.py#L571)

( metric\_info\_dir )

Create MetricInfo from the JSON file in `metric_info_dir`.

Example:

Copied

```
>>> from datasets import MetricInfo
>>> metric_info = MetricInfo.from_directory("/path/to/directory/")
```

**write\_to\_directory**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/info.py#L551)

( metric\_info\_dirpretty\_print = False )

Write `MetricInfo` as JSON to `metric_info_dir`. Also save the license separately in LICENCE. If `pretty_print` is True, the JSON will be pretty-printed with the indent level of 4.

Example:

Copied

```
>>> from datasets import load_metric
>>> metric = load_metric("accuracy")
>>> metric.info.write_to_directory("/path/to/directory/")
```

### Metric

The base class `Metric` implements a Metric backed by one or several [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset).

#### class datasets.Metric

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/metric.py#L146)

( config\_name: typing.Optional\[str] = Nonekeep\_in\_memory: bool = Falsecache\_dir: typing.Optional\[str] = Nonenum\_process: int = 1process\_id: int = 0seed: typing.Optional\[int] = Noneexperiment\_id: typing.Optional\[str] = Nonemax\_concurrent\_cache\_files: int = 10000timeout: typing.Union\[int, float] = 100\*\*kwargs )

Parameters

* **config\_name** (`str`) — This is used to define a hash specific to a metrics computation script and prevents the metric’s data to be overridden when the metric loading script is modified.
* **keep\_in\_memory** (`bool`) — keep all predictions and references in memory. Not possible in distributed settings.
* **cache\_dir** (`str`) — Path to a directory in which temporary prediction/references data will be stored. The data directory should be located on a shared file-system in distributed setups.
* **num\_process** (`int`) — specify the total number of nodes in a distributed settings. This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1).
* **process\_id** (`int`) — specify the id of the current process in a distributed setup (between 0 and num\_process-1) This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1).
* **seed** (`int`, optional) — If specified, this will temporarily set numpy’s random seed when [datasets.Metric.compute()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Metric.compute) is run.
* **experiment\_id** (`str`) — A specific experiment id. This is used if several distributed evaluations share the same file system. This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1).
* **max\_concurrent\_cache\_files** (`int`) — Max number of concurrent metrics cache files (default 10000).
* **timeout** (`Union[int, float]`) — Timeout in second for distributed setting synchronization.

A Metric is the base class and common API for all metrics.

Deprecated in 2.5.0

Use the new library 🌍 Evaluate instead: [https://boincai.com/docs/evaluate](https://huggingface.co/docs/evaluate)

**add**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/metric.py#L521)

( prediction = Nonereference = None\*\*kwargs )

Parameters

* **prediction** (list/array/tensor, optional) — Predictions.
* **reference** (list/array/tensor, optional) — References.

Add one prediction and reference for the metric’s stack.

Example:

Copied

```
>>> from datasets import load_metric
>>> metric = load_metric("accuracy")
>>> metric.add(predictions=model_predictions, references=labels)
```

**add\_batch**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/metric.py#L474)

( predictions = Nonereferences = None\*\*kwargs )

Parameters

* **predictions** (list/array/tensor, optional) — Predictions.
* **references** (list/array/tensor, optional) — References.

Add a batch of predictions and references for the metric’s stack.

Example:

Copied

```
>>> from datasets import load_metric
>>> metric = load_metric("accuracy")
>>> metric.add_batch(predictions=model_prediction, references=labels)
```

**compute**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/metric.py#L403)

( predictions = Nonereferences = None\*\*kwargs )

Parameters

* **predictions** (list/array/tensor, optional) — Predictions.
* **references** (list/array/tensor, optional) — References.
* \***\*kwargs** (optional) — Keyword arguments that will be forwarded to the metrics `_compute` method (see details in the docstring).

Compute the metrics.

Usage of positional arguments is not allowed to prevent mistakes.

Example:

Copied

```
>>> from datasets import load_metric
>>> metric = load_metric("accuracy")
>>> accuracy = metric.compute(predictions=model_prediction, references=labels)
```

**download\_and\_prepare**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/metric.py#L604)

( download\_config: typing.Optional\[datasets.download.download\_config.DownloadConfig] = Nonedl\_manager: typing.Optional\[datasets.download.download\_manager.DownloadManager] = None )

Parameters

* **download\_config** ([DownloadConfig](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.DownloadConfig), optional) — Specific download configuration parameters.
* **dl\_manager** ([DownloadManager](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.DownloadManager), optional) — Specific download manager to use.

Downloads and prepares dataset for reading.

### Filesystems

#### class datasets.filesystems.S3FileSystem

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/filesystems/s3filesystem.py#L7)

( \*args\*\*kwargs )

Parameters

* **anon** (`bool`, default to `False`) — Whether to use anonymous connection (public buckets only). If `False`, uses the key/secret given, or boto’s credential resolver (client\_kwargs, environment, variables, config files, EC2 IAM server, in that order).
* **key** (`str`) — If not anonymous, use this access key ID, if specified.
* **secret** (`str`) — If not anonymous, use this secret access key, if specified.
* **token** (`str`) — If not anonymous, use this security token, if specified.
* **use\_ssl** (`bool`, defaults to `True`) — Whether to use SSL in connections to S3; may be faster without, but insecure. If `use_ssl` is also set in `client_kwargs`, the value set in `client_kwargs` will take priority.
* **s3\_additional\_kwargs** (`dict`) — Parameters that are used when calling S3 API methods. Typically used for things like ServerSideEncryption.
* **client\_kwargs** (`dict`) — Parameters for the botocore client.
* **requester\_pays** (`bool`, defaults to `False`) — Whether `RequesterPays` buckets are supported.
* **default\_block\_size** (`int`) — If given, the default block size value used for `open()`, if no specific value is given at all time. The built-in default is 5MB.
* **default\_fill\_cache** (`bool`, defaults to `True`) — Whether to use cache filling with open by default. Refer to `S3File.open`.
* **default\_cache\_type** (`str`, defaults to `bytes`) — If given, the default `cache_type` value used for `open()`. Set to `none` if no caching is desired. See fsspec’s documentation for other available `cache_type` values.
* **version\_aware** (`bool`, defaults to `False`) — Whether to support bucket versioning. If enable this will require the user to have the necessary IAM permissions for dealing with versioned objects.
* **cache\_regions** (`bool`, defaults to `False`) — Whether to cache bucket regions. Whenever a new bucket is used, it will first find out which region it belongs to and then use the client for that region.
* **asynchronous** (`bool`, defaults to `False`) — Whether this instance is to be used from inside coroutines.
* **config\_kwargs** (`dict`) — Parameters passed to `botocore.client.Config`. \*\*kwargs — Other parameters for core session.
* **session** (`aiobotocore.session.AioSession`) — Session to be used for all connections. This session will be used inplace of creating a new session inside S3FileSystem. For example: `aiobotocore.session.AioSession(profile='test_user')`.
* **skip\_instance\_cache** (`bool`) — Control reuse of instances. Passed on to `fsspec`.
* **use\_listings\_cache** (`bool`) — Control reuse of directory listings. Passed on to `fsspec`.
* **listings\_expiry\_time** (`int` or `float`) — Control reuse of directory listings. Passed on to `fsspec`.
* **max\_paths** (`int`) — Control reuse of directory listings. Passed on to `fsspec`.

`datasets.filesystems.S3FileSystem` is a subclass of [`s3fs.S3FileSystem`](https://s3fs.readthedocs.io/en/latest/api.html).

Users can use this class to access S3 as if it were a file system. It exposes a filesystem-like API (ls, cp, open, etc.) on top of S3 storage. Provide credentials either explicitly (`key=`, `secret=`) or with boto’s credential methods. See botocore documentation for more information. If no credentials are available, use `anon=True`.

Examples:

Listing files from public S3 bucket.

Copied

```
>>> import datasets
>>> s3 = datasets.filesystems.S3FileSystem(anon=True)
>>> s3.ls('public-datasets/imdb/train')
['dataset_info.json.json','dataset.arrow','state.json']
```

Listing files from private S3 bucket using `aws_access_key_id` and `aws_secret_access_key`.

Copied

```
>>> import datasets
>>> s3 = datasets.filesystems.S3FileSystem(key=aws_access_key_id, secret=aws_secret_access_key)
>>> s3.ls('my-private-datasets/imdb/train')
['dataset_info.json.json','dataset.arrow','state.json']
```

Using `S3Filesystem` with `botocore.session.Session` and custom `aws_profile`.

Copied

```
>>> import botocore
>>> from datasets.filesystems import S3Filesystem

>>> s3_session = botocore.session.Session(profile_name='my_profile_name')
>>> s3 = S3FileSystem(session=s3_session)
```

Loading dataset from S3 using `S3Filesystem` and [load\_from\_disk()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/loading_methods#datasets.load_from_disk).

Copied

```
>>> from datasets import load_from_disk
>>> from datasets.filesystems import S3Filesystem

>>> s3 = S3FileSystem(key=aws_access_key_id, secret=aws_secret_access_key)
>>> dataset = load_from_disk('s3://my-private-datasets/imdb/train', storage_options=s3.storage_options)
>>> print(len(dataset))
25000
```

Saving dataset to S3 using `S3Filesystem` and [Dataset.save\_to\_disk()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset.save_to_disk).

Copied

```
>>> from datasets import load_dataset
>>> from datasets.filesystems import S3Filesystem

>>> dataset = load_dataset("imdb")
>>> s3 = S3FileSystem(key=aws_access_key_id, secret=aws_secret_access_key)
>>> dataset.save_to_disk('s3://my-private-datasets/imdb/train', storage_options=s3.storage_options)
```

**datasets.filesystems.extract\_path\_from\_uri**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/filesystems/__init__.py#L33)

( dataset\_path: str )

Parameters

* **dataset\_path** (`str`) — Path (e.g. `dataset/train`) or remote uri (e.g. `s3://my-bucket/dataset/train`) of the dataset directory.

Preprocesses `dataset_path` and removes remote filesystem (e.g. removing `s3://`).

**datasets.filesystems.is\_remote\_filesystem**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/filesystems/__init__.py#L46)

( fs: AbstractFileSystem )

Parameters

* **fs** (`fsspec.spec.AbstractFileSystem`) — An abstract super-class for pythonic file-systems, e.g. `fsspec.filesystem('file')` or [datasets.filesystems.S3FileSystem](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.filesystems.S3FileSystem).

Validates if filesystem has remote protocol.

### Fingerprint

#### class datasets.fingerprint.Hasher

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/fingerprint.py#L211)

( )

Hasher that accepts python objects as inputs.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://boinc-ai.gitbook.io/datasets/reference/main-classes.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
