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
(
self,
dim: Mapping[Any, Sequence[Hashable]] | None = None,
create_index: bool | None = True,
index_cls: type[Index] = PandasMultiIndex,
**dim_kwargs: Sequence[Hashable | EllipsisType],
)
| 2924 | |
| 2925 | @partial(deprecate_dims, old_name="dimensions") |
| 2926 | def stack( |
| 2927 | self, |
| 2928 | dim: Mapping[Any, Sequence[Hashable]] | None = None, |
| 2929 | create_index: bool | None = True, |
| 2930 | index_cls: type[Index] = PandasMultiIndex, |
| 2931 | **dim_kwargs: Sequence[Hashable | EllipsisType], |
| 2932 | ) -> Self: |
| 2933 | """ |
| 2934 | Stack any number of existing dimensions into a single new dimension. |
| 2935 | |
| 2936 | New dimensions will be added at the end, and the corresponding |
| 2937 | coordinate variables will be combined into a MultiIndex. |
| 2938 | |
| 2939 | Parameters |
| 2940 | ---------- |
| 2941 | dim : mapping of Hashable to sequence of Hashable |
| 2942 | Mapping of the form `new_name=(dim1, dim2, ...)`. |
| 2943 | Names of new dimensions, and the existing dimensions that they |
| 2944 | replace. An ellipsis (`...`) will be replaced by all unlisted dimensions. |
| 2945 | Passing a list containing an ellipsis (`stacked_dim=[...]`) will stack over |
| 2946 | all dimensions. |
| 2947 | create_index : bool or None, default: True |
| 2948 | If True, create a multi-index for each of the stacked dimensions. |
| 2949 | If False, don't create any index. |
| 2950 | If None, create a multi-index only if exactly one single (1-d) coordinate |
| 2951 | index is found for every dimension to stack. |
| 2952 | index_cls: class, optional |
| 2953 | Can be used to pass a custom multi-index type. Must be an Xarray index that |
| 2954 | implements `.stack()`. By default, a pandas multi-index wrapper is used. |
| 2955 | **dim_kwargs |
| 2956 | The keyword arguments form of ``dim``. |
| 2957 | One of dim or dim_kwargs must be provided. |
| 2958 | |
| 2959 | Returns |
| 2960 | ------- |
| 2961 | stacked : DataArray |
| 2962 | DataArray with stacked data. |
| 2963 | |
| 2964 | Examples |
| 2965 | -------- |
| 2966 | >>> arr = xr.DataArray( |
| 2967 | ... np.arange(6).reshape(2, 3), |
| 2968 | ... coords=[("x", ["a", "b"]), ("y", [0, 1, 2])], |
| 2969 | ... ) |
| 2970 | >>> arr |
| 2971 | <xarray.DataArray (x: 2, y: 3)> Size: 48B |
| 2972 | array([[0, 1, 2], |
| 2973 | [3, 4, 5]]) |
| 2974 | Coordinates: |
| 2975 | * x (x) <U1 8B 'a' 'b' |
| 2976 | * y (y) int64 24B 0 1 2 |
| 2977 | >>> stacked = arr.stack(z=("x", "y")) |
| 2978 | >>> stacked.indexes["z"] |
| 2979 | MultiIndex([('a', 0), |
| 2980 | ('a', 1), |
| 2981 | ('a', 2), |
| 2982 | ('b', 0), |
| 2983 | ('b', 1), |