diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index 192d73a63d3..37369afbf96 100644 --- a/xarray/core/dataarray.py +++ b/xarray/core/dataarray.py @@ -534,10 +534,10 @@ def _replace_maybe_drop_dims( variable: Variable, name: Hashable | None | Default = _default, ) -> Self: - if variable.dims == self.dims and variable.shape == self.shape: + if self.sizes == variable.sizes: coords = self._coords.copy() indexes = self._indexes - elif variable.dims == self.dims: + elif set(self.dims) == set(variable.dims): # Shape has changed (e.g. from reduce(..., keepdims=True) new_sizes = dict(zip(self.dims, variable.shape, strict=True)) coords = { diff --git a/xarray/tests/test_groupby.py b/xarray/tests/test_groupby.py index 9d9c22cfa96..dc869cc3a34 100644 --- a/xarray/tests/test_groupby.py +++ b/xarray/tests/test_groupby.py @@ -2919,3 +2919,16 @@ def test_gappy_resample_reductions(reduction): # 1. lambda x: x # 2. grouped-reduce on unique coords is identical to array # 3. group_over == groupby-reduce along other dimensions + + +def test_groupby_transpose(): + # GH5361 + data = xr.DataArray( + np.random.randn(4, 2), + dims=["x", "z"], + coords={"x": ["a", "b", "a", "c"], "y": ("x", [0, 1, 0, 2])}, + ) + first = data.T.groupby("x").sum() + second = data.groupby("x").sum() + + assert_identical(first, second.transpose(*first.dims))