diff --git a/doc/whats-new.rst b/doc/whats-new.rst index c1440ec1108..126ea28d416 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -160,6 +160,8 @@ Bug fixes By `Mathias Hauser `_. - Fix html repr in untrusted notebooks: fallback to plain text repr. (:pull:`4053`) By `Benoit Bovy `_. +- Fix :py:meth:`DataArray.to_unstacked_dataset` for single-dimension variables. (:issue:`4049`) + By `Deepak Cherian `_ - Fix :py:func:`open_rasterio` for ``WarpedVRT`` with specified ``src_crs``. (:pull:`4104`) By `Dave Cole `_. diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index b0df874953b..3be9bb79c60 100644 --- a/xarray/core/dataarray.py +++ b/xarray/core/dataarray.py @@ -1961,7 +1961,7 @@ def to_unstacked_dataset(self, dim, level=0): # pull variables out of datarray data_dict = {} for k in variables: - data_dict[k] = self.sel({variable_dim: k}).squeeze(drop=True) + data_dict[k] = self.sel({variable_dim: k}, drop=True).squeeze(drop=True) # unstacked dataset return Dataset(data_dict) diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index 9c8d40724da..9d2623d99e8 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -3031,6 +3031,14 @@ def test_to_stacked_array_dtype_dims(self): assert y.dims == ("x", "features") def test_to_stacked_array_to_unstacked_dataset(self): + + # single dimension: regression test for GH4049 + arr = xr.DataArray(np.arange(3), coords=[("x", [0, 1, 2])]) + data = xr.Dataset({"a": arr, "b": arr}) + stacked = data.to_stacked_array("y", sample_dims=["x"]) + unstacked = stacked.to_unstacked_dataset("y") + assert_identical(unstacked, data) + # make a two dimensional dataset a, b = create_test_stacked_array() D = xr.Dataset({"a": a, "b": b})