Skip to content

Fix reduction by subset of grouper dimensions #10258

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions xarray/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ def check_reduce_dims(reduce_dims, dimensions):
if any(dim not in dimensions for dim in reduce_dims):
raise ValueError(
f"cannot reduce over dimensions {reduce_dims!r}. expected either '...' "
f"to reduce over all dimensions or one or more of {dimensions!r}."
f"to reduce over all dimensions or one or more of {dimensions!r}. "
f"Alternatively, install the `flox` package. "
)


Expand Down Expand Up @@ -1126,7 +1127,7 @@ def _flox_reduce(
group_dims = set(grouper.group.dims)
new_coords = []
to_drop = []
if group_dims.issubset(set(parsed_dim)):
if group_dims & set(parsed_dim):
for grouper in self.groupers:
output_index = grouper.full_index
if isinstance(output_index, pd.RangeIndex):
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 @@ -1640,6 +1640,19 @@ def test_groupby_multidim(self) -> None:
actual_sum = array.groupby(dim).sum(...)
assert_identical(expected_sum, actual_sum)

if has_flox:
# GH9803
# reduce over one dim of a nD grouper
array.coords["labels"] = (("ny", "nx"), np.array([["a", "b"], ["b", "a"]]))
actual = array.groupby("labels").sum("nx")
expected_np = np.array([[[0, 1], [3, 2]], [[5, 10], [20, 15]]])
expected = xr.DataArray(
expected_np,
dims=("time", "ny", "labels"),
coords={"labels": ["a", "b"]},
)
assert_identical(expected, actual)

def test_groupby_multidim_map(self) -> None:
array = self.make_groupby_multidim_example_array()
actual = array.groupby("lon").map(lambda x: x - x.mean())
Expand Down
Loading