stack

UnitsAwareDataArray.stack(dim: Mapping[Any, Sequence[Hashable]] | None = None, create_index: bool | None = True, index_cls: type[Index] = <class 'xarray.core.indexes.PandasMultiIndex'>, **dim_kwargs: Sequence[Hashable]) Self

Stack any number of existing dimensions into a single new dimension.

New dimensions will be added at the end, and the corresponding coordinate variables will be combined into a MultiIndex.

Parameters:
  • dim (mapping of Hashable to sequence of Hashable) – Mapping of the form new_name=(dim1, dim2, …). Names of new dimensions, and the existing dimensions that they replace. An ellipsis () will be replaced by all unlisted dimensions. Passing a list containing an ellipsis (stacked_dim=[…]) will stack over all dimensions.

  • create_index (bool or None, default: True) – If True, create a multi-index for each of the stacked dimensions. If False, don’t create any index. If None, create a multi-index only if exactly one single (1-d) coordinate index is found for every dimension to stack.

  • index_cls (class, optional) – Can be used to pass a custom multi-index type. Must be an Xarray index that implements .stack(). By default, a pandas multi-index wrapper is used.

  • **dim_kwargs – The keyword arguments form of dim. One of dim or dim_kwargs must be provided.

Returns:

stacked – DataArray with stacked data.

Return type:

DataArray

Examples

>>> arr = xr.DataArray(
...     np.arange(6).reshape(2, 3),
...     coords=[("x", ["a", "b"]), ("y", [0, 1, 2])],
... )
>>> arr
<xarray.DataArray (x: 2, y: 3)> Size: 48B
array([[0, 1, 2],
       [3, 4, 5]])
Coordinates:
  * x        (x) <U1 8B 'a' 'b'
  * y        (y) int64 24B 0 1 2
>>> stacked = arr.stack(z=("x", "y"))
>>> stacked.indexes["z"]
MultiIndex([('a', 0),
            ('a', 1),
            ('a', 2),
            ('b', 0),
            ('b', 1),
            ('b', 2)],
           name='z')

See also

DataArray.unstack