🍾 Xarray is now 10 years old! 🎉

xarray.Dataset.set_index

xarray.Dataset.set_index#

Dataset.set_index(indexes=None, append=False, **indexes_kwargs)[source]#

Set Dataset (multi-)indexes using one or more existing coordinates or variables.

This legacy method is limited to pandas (multi-)indexes and 1-dimensional “dimension” coordinates. See set_xindex() for setting a pandas or a custom Xarray-compatible index from one or more arbitrary coordinates.

Parameters:
  • indexes ({dim: index, ...}) – Mapping from names matching dimensions and values given by (lists of) the names of existing coordinates or variables to set as new (multi-)index.

  • append (bool, default: False) – If True, append the supplied index(es) to the existing index(es). Otherwise replace the existing index(es) (default).

  • **indexes_kwargs (optional) – The keyword arguments form of indexes. One of indexes or indexes_kwargs must be provided.

Returns:

obj (Dataset) – Another dataset, with this dataset’s data but replaced coordinates.

Examples

>>> arr = xr.DataArray(
...     data=np.ones((2, 3)),
...     dims=["x", "y"],
...     coords={"x": range(2), "y": range(3), "a": ("x", [3, 4])},
... )
>>> ds = xr.Dataset({"v": arr})
>>> ds
<xarray.Dataset> Size: 104B
Dimensions:  (x: 2, y: 3)
Coordinates:
  * x        (x) int64 16B 0 1
  * y        (y) int64 24B 0 1 2
    a        (x) int64 16B 3 4
Data variables:
    v        (x, y) float64 48B 1.0 1.0 1.0 1.0 1.0 1.0
>>> ds.set_index(x="a")
<xarray.Dataset> Size: 88B
Dimensions:  (x: 2, y: 3)
Coordinates:
  * x        (x) int64 16B 3 4
  * y        (y) int64 24B 0 1 2
Data variables:
    v        (x, y) float64 48B 1.0 1.0 1.0 1.0 1.0 1.0