diff --git a/xarray/core/groupby.py b/xarray/core/groupby.py index 57802c199e1..a5482c5a514 100644 --- a/xarray/core/groupby.py +++ b/xarray/core/groupby.py @@ -828,7 +828,7 @@ def groups(self) -> dict[GroupKey, GroupIndex]: self._groups = dict( zip( self.encoded.unique_coord.data, - self.encoded.group_indices, + tuple(g for g in self.encoded.group_indices if g), strict=True, ) ) diff --git a/xarray/tests/test_groupby.py b/xarray/tests/test_groupby.py index 202b729abcf..336a5e6c91c 100644 --- a/xarray/tests/test_groupby.py +++ b/xarray/tests/test_groupby.py @@ -3200,6 +3200,16 @@ def test_multiple_grouper_unsorted_order() -> None: assert_identical(actual2, expected2) +def test_multiple_grouper_empty_groups() -> None: + ds = xr.Dataset( + {"foo": (("x", "y"), np.random.rand(4, 3))}, + coords={"x": [10, 20, 30, 40], "letters": ("x", list("abba"))}, + ) + + groups = ds.groupby(x=BinGrouper(bins=[5, 15, 25]), letters=UniqueGrouper()) + assert len(groups.groups) == 2 + + def test_groupby_multiple_bin_grouper_missing_groups() -> None: from numpy import nan