Skip to content

Commit

Permalink
Make _replace more lenient.
Browse files Browse the repository at this point in the history
Closes #5361
  • Loading branch information
dcherian committed Sep 18, 2024
1 parent e313853 commit 6033bc9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
8 changes: 6 additions & 2 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,10 +534,14 @@ def _replace_maybe_drop_dims(
variable: Variable,
name: Hashable | None | Default = _default,
) -> Self:
if variable.dims == self.dims and variable.shape == self.shape:
dims_are_equal = set(variable.dims) == set(self.dims)
size_is_equal = (
self.sizes[dim] == size for dim, size in variable.sizes.items()
)
if dims_are_equal and all(size_is_equal):
coords = self._coords.copy()
indexes = self._indexes
elif variable.dims == self.dims:
elif dims_are_equal:
# Shape has changed (e.g. from reduce(..., keepdims=True)
new_sizes = dict(zip(self.dims, variable.shape, strict=True))
coords = {
Expand Down
13 changes: 13 additions & 0 deletions xarray/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2918,3 +2918,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))

0 comments on commit 6033bc9

Please sign in to comment.