From 89880b529065f8324c19bc5dfd78bd488607aebf Mon Sep 17 00:00:00 2001 From: dcherian Date: Mon, 8 May 2023 17:14:18 -0600 Subject: [PATCH 1/3] Fix .groupby(multi index level) Closes #6836 --- xarray/core/groupby.py | 2 +- xarray/tests/test_groupby.py | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/xarray/core/groupby.py b/xarray/core/groupby.py index 55fe103d41e..ac21cb03093 100644 --- a/xarray/core/groupby.py +++ b/xarray/core/groupby.py @@ -381,7 +381,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 a8530d85235..13c2c82e3b0 100644 --- a/xarray/tests/test_groupby.py +++ b/xarray/tests/test_groupby.py @@ -2336,3 +2336,11 @@ def test_groupby_binary_op_regression() -> None: anom_gb = x_slice.groupby("time.month") - clim assert_identical(xr.zeros_like(anom_gb), anom_gb) + + +def test_groupby_multiindex_level(): + # 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]} From 2697cee3b795f6864b5695a79fd83e5d4fb3cc86 Mon Sep 17 00:00:00 2001 From: Illviljan <14371165+Illviljan@users.noreply.github.com> Date: Fri, 12 May 2023 06:41:43 +0200 Subject: [PATCH 2/3] Update xarray/tests/test_groupby.py --- xarray/tests/test_groupby.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xarray/tests/test_groupby.py b/xarray/tests/test_groupby.py index bacb9d0e104..8a93cf930a5 100644 --- a/xarray/tests/test_groupby.py +++ b/xarray/tests/test_groupby.py @@ -2340,7 +2340,7 @@ def test_groupby_binary_op_regression() -> None: assert_identical(xr.zeros_like(anom_gb), anom_gb) -def test_groupby_multiindex_level(): +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))]) From dc7f6383fca6d0ed52c3fd727fe7b16c45bef478 Mon Sep 17 00:00:00 2001 From: dcherian Date: Fri, 12 May 2023 10:11:42 -0600 Subject: [PATCH 3/3] mypy: Add _DummyGroup.to_index --- xarray/core/groupby.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/xarray/core/groupby.py b/xarray/core/groupby.py index 1f18396725e..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