Skip to content

Grouper tweaks. #10362

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 2 commits into from
May 30, 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
9 changes: 8 additions & 1 deletion xarray/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ def _parse_group_and_groupers(
) -> tuple[ResolvedGrouper, ...]:
from xarray.core.dataarray import DataArray
from xarray.core.variable import Variable
from xarray.groupers import UniqueGrouper
from xarray.groupers import Grouper, UniqueGrouper

if group is not None and groupers:
raise ValueError(
Expand All @@ -402,6 +402,13 @@ def _parse_group_and_groupers(
f"`group` must be a DataArray. Received {type(group).__name__!r} instead"
)

if isinstance(group, Grouper):
raise TypeError(
"Cannot group by a Grouper object. "
f"Instead use `.groupby(var_name={type(group).__name__}(...))`. "
"You may need to assign the variable you're grouping by as a coordinate using `assign_coords`."
)

if isinstance(group, Mapping):
grouper_mapping = either_dict_or_kwargs(group, groupers, "groupby")
group = None
Expand Down
2 changes: 1 addition & 1 deletion xarray/groupers.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ class UniqueGrouper(Grouper):
present in ``labels`` will be ignored.
"""

_group_as_index: pd.Index | None = field(default=None, repr=False)
_group_as_index: pd.Index | None = field(default=None, repr=False, init=False)
labels: ArrayLike | None = field(default=None)

@property
Expand Down
6 changes: 6 additions & 0 deletions xarray/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,12 @@ def test_groupby_grouping_errors() -> None:
with pytest.raises(ValueError, match=r"Failed to group data."):
dataset.to_dataarray().groupby(dataset.foo * np.nan)

with pytest.raises(TypeError, match=r"Cannot group by a Grouper object"):
dataset.groupby(UniqueGrouper(labels=[1, 2, 3])) # type: ignore[arg-type]

with pytest.raises(TypeError, match=r"got multiple values for argument"):
UniqueGrouper(dataset.x, labels=[1, 2, 3]) # type: ignore[misc]


def test_groupby_reduce_dimension_error(array) -> None:
grouped = array.groupby("y")
Expand Down
Loading