MCPcopy
hub / github.com/pydata/xarray / to_unstacked_dataset

Method to_unstacked_dataset

xarray/core/dataarray.py:3063–3126  ·  view source on GitHub ↗

Unstack DataArray expanding to Dataset along a given level of a stacked coordinate. This is the inverse operation of Dataset.to_stacked_array. Parameters ---------- dim : Hashable Name of existing dimension to unstack level : int or Hasha

(self, dim: Hashable, level: int | Hashable = 0)

Source from the content-addressed store, hash-verified

3061 return self._from_temp_dataset(ds)
3062
3063 def to_unstacked_dataset(self, dim: Hashable, level: int | Hashable = 0) -> Dataset:
3064 """Unstack DataArray expanding to Dataset along a given level of a
3065 stacked coordinate.
3066
3067 This is the inverse operation of Dataset.to_stacked_array.
3068
3069 Parameters
3070 ----------
3071 dim : Hashable
3072 Name of existing dimension to unstack
3073 level : int or Hashable, default: 0
3074 The MultiIndex level to expand to a dataset along. Can either be
3075 the integer index of the level or its name.
3076
3077 Returns
3078 -------
3079 unstacked: Dataset
3080
3081 Examples
3082 --------
3083 >>> arr = xr.DataArray(
3084 ... np.arange(6).reshape(2, 3),
3085 ... coords=[("x", ["a", "b"]), ("y", [0, 1, 2])],
3086 ... )
3087 >>> data = xr.Dataset({"a": arr, "b": arr.isel(y=0)})
3088 >>> data
3089 <xarray.Dataset> Size: 96B
3090 Dimensions: (x: 2, y: 3)
3091 Coordinates:
3092 * x (x) <U1 8B 'a' 'b'
3093 * y (y) int64 24B 0 1 2
3094 Data variables:
3095 a (x, y) int64 48B 0 1 2 3 4 5
3096 b (x) int64 16B 0 3
3097 >>> stacked = data.to_stacked_array("z", ["x"])
3098 >>> stacked.indexes["z"]
3099 MultiIndex([('a', 0.0),
3100 ('a', 1.0),
3101 ('a', 2.0),
3102 ('b', nan)],
3103 name='z')
3104 >>> roundtripped = stacked.to_unstacked_dataset(dim="z")
3105 >>> data.identical(roundtripped)
3106 True
3107
3108 See Also
3109 --------
3110 Dataset.to_stacked_array
3111 """
3112 idx = self._indexes[dim].to_pandas_index()
3113 if not isinstance(idx, pd.MultiIndex):
3114 raise ValueError(f"'{dim}' is not a stacked coordinate")
3115
3116 level_number = idx._get_level_number(level) # type: ignore[attr-defined]
3117 variables = idx.levels[level_number]
3118 variable_dim = idx.names[level_number]
3119
3120 # pull variables out of datarray

Calls 4

selMethod · 0.95
DatasetClass · 0.90
to_pandas_indexMethod · 0.45
squeezeMethod · 0.45