From 3c74509c79c4e55f2f992633e8db9911b1e4f2f4 Mon Sep 17 00:00:00 2001 From: Deepak Cherian Date: Thu, 19 Sep 2024 07:39:29 -0600 Subject: [PATCH] Make _replace more lenient. (#9517) * Make _replace more lenient. Closes #5361 * review comments --- xarray/core/dataarray.py | 4 ++-- xarray/tests/test_groupby.py | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) 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))