xarray.DataArray.unstack#
- DataArray.unstack(dim=None, *, fill_value=<NA>, sparse=False)[source]#
Unstack existing dimensions corresponding to MultiIndexes.
The dimensions are unstacked into multiple new dimensions.
New dimensions will be added at the end.
- Parameters:
dim (
str,IterableofHashableorNone, optional) – Dimension(s) over which to unstack. By default unstacks all MultiIndexes.fill_value (scalar or dict-like, default:
nan) – Value to be filled. If a dict-like, maps variable names to fill values. Use the data array’s name to refer to its name. If not provided or if the dict-like does not contain all variables, the dtype’s NA value will be used.
- Returns:
unstacked (
DataArray) – Array with unstacked data.
See also
Notes
The order of the new dimension coordinates follows the levels of the
MultiIndex. AMultiIndexcreated by pandas (e.g. when converting apd.Serieswith aMultiIndex) usually has sorted levels, so the resulting coordinates will be sorted. AMultiIndexcreated byDataArray.stack()preserves the original order. UseDataArray.sel()after unstacking to select a specific order if needed.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') >>> roundtripped = stacked.unstack() >>> arr.identical(roundtripped) True