diff --git a/xarray/core/groupby.py b/xarray/core/groupby.py index 85ea0b5fddc..1bda5568c9a 100644 --- a/xarray/core/groupby.py +++ b/xarray/core/groupby.py @@ -236,6 +236,10 @@ def __getitem__(self, key): key = key[0] return self.values[key] + def to_index(self) -> pd.Index: + # could be pd.RangeIndex? + return pd.Index(np.arange(self.size)) + def copy(self, deep: bool = True, data: Any = None): raise NotImplementedError @@ -381,7 +385,7 @@ def is_unique_and_monotonic(self) -> bool: @property def group_as_index(self) -> pd.Index: if self._group_as_index is None: - self._group_as_index = safe_cast_to_index(self.group1d) + self._group_as_index = self.group1d.to_index() return self._group_as_index diff --git a/xarray/tests/test_groupby.py b/xarray/tests/test_groupby.py index 97ba0b585e8..8a93cf930a5 100644 --- a/xarray/tests/test_groupby.py +++ b/xarray/tests/test_groupby.py @@ -2340,6 +2340,14 @@ def test_groupby_binary_op_regression() -> None: assert_identical(xr.zeros_like(anom_gb), anom_gb) +def test_groupby_multiindex_level() -> None: + # GH6836 + midx = pd.MultiIndex.from_product([list("abc"), [0, 1]], names=("one", "two")) + mda = xr.DataArray(np.random.rand(6, 3), [("x", midx), ("y", range(3))]) + groups = mda.groupby("one").groups + assert groups == {"a": [0, 1], "b": [2, 3], "c": [4, 5]} + + @requires_flox @pytest.mark.parametrize("func", ["sum", "prod"]) @pytest.mark.parametrize("skipna", [True, False])