Skip to content

Commit c668582

Browse files
dcherianIllviljan
andauthored
Fix .groupby(multi index level) (#7830)
* Fix .groupby(multi index level) Closes #6836 * Update xarray/tests/test_groupby.py * mypy: Add _DummyGroup.to_index --------- Co-authored-by: Illviljan <[email protected]>
1 parent 46ef0ca commit c668582

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

xarray/core/groupby.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,10 @@ def __getitem__(self, key):
236236
key = key[0]
237237
return self.values[key]
238238

239+
def to_index(self) -> pd.Index:
240+
# could be pd.RangeIndex?
241+
return pd.Index(np.arange(self.size))
242+
239243
def copy(self, deep: bool = True, data: Any = None):
240244
raise NotImplementedError
241245

@@ -381,7 +385,7 @@ def is_unique_and_monotonic(self) -> bool:
381385
@property
382386
def group_as_index(self) -> pd.Index:
383387
if self._group_as_index is None:
384-
self._group_as_index = safe_cast_to_index(self.group1d)
388+
self._group_as_index = self.group1d.to_index()
385389
return self._group_as_index
386390

387391

xarray/tests/test_groupby.py

+8
Original file line numberDiff line numberDiff line change
@@ -2340,6 +2340,14 @@ def test_groupby_binary_op_regression() -> None:
23402340
assert_identical(xr.zeros_like(anom_gb), anom_gb)
23412341

23422342

2343+
def test_groupby_multiindex_level() -> None:
2344+
# GH6836
2345+
midx = pd.MultiIndex.from_product([list("abc"), [0, 1]], names=("one", "two"))
2346+
mda = xr.DataArray(np.random.rand(6, 3), [("x", midx), ("y", range(3))])
2347+
groups = mda.groupby("one").groups
2348+
assert groups == {"a": [0, 1], "b": [2, 3], "c": [4, 5]}
2349+
2350+
23432351
@requires_flox
23442352
@pytest.mark.parametrize("func", ["sum", "prod"])
23452353
@pytest.mark.parametrize("skipna", [True, False])

0 commit comments

Comments
 (0)