8000 Grouper tweaks. (#10362) · pydata/xarray@42836f3 · GitHub
[go: up one dir, main page]

Skip to content

Commit 42836f3

Browse files
Grouper tweaks. (#10362)
Co-authored-by: Kai Mühlbauer <kai.muehlbauer@uni-bonn.de>
1 parent 59e98f1 commit 42836f3

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

xarray/core/groupby.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ def _parse_group_and_groupers(
387387
) -> tuple[ResolvedGrouper, ...]:
388388
from xarray.core.dataarray import DataArray
389389
from xarray.core.variable import Variable
390-
from xarray.groupers import UniqueGrouper
390+
from xarray.groupers import Grouper, UniqueGrouper
391391

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

405+
if isinstance(group, Grouper):
406+
raise TypeError(
407+
"Cannot group by a Grouper object. "
408+
f"Instead use `.groupby(var_name={type(group).__name__}(...))`. "
409+
"You may need to assign the variable you're grouping by as a coordinate using `assign_coords`."
410+
)
411+
405412
if isinstance(group, Mapping):
406413
grouper_mapping = either_dict_or_kwargs(group, groupers, "groupby")
407414
group = None

xarray/groupers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ class UniqueGrouper(Grouper):
186186
present in ``labels`` will be ignored.
187187
"""
188188

189-
_group_as_index: pd.Index | None = field(default=None, repr=False)
189+
_group_as_index: pd.Index | None = field(default=None, repr=False, init=False)
190190
labels: ArrayLike | None = field(default=None)
191191

192192
@property

xarray/tests/test_groupby.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -757,6 +757,12 @@ def test_groupby_grouping_errors() -> None:
757757
with pytest.raises(ValueError, match=r"Failed to group data."):
758758
dataset.to_dataarray().groupby(dataset.foo * np.nan)
759759

760+
with pytest.raises(TypeError, match=r"Cannot group by a Grouper object"):
761+
dataset.groupby(UniqueGrouper(labels=[1, 2, 3])) # type: ignore[arg-type]
762+
763+
with pytest.raises(TypeError, match=r"got multiple values for argument"):
764+
UniqueGrouper(dataset.x, labels=[1, 2, 3]) # type: ignore[misc]
765+
760766

761767
def test_groupby_reduce_dimension_error(array) -> None:
762768
grouped = array.groupby("y")

0 commit comments

Comments
 (0)
0