Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix .groupby(multi index level) #7830

Merged
merged 5 commits into from
Jun 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion xarray/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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


Expand Down
8 changes: 8 additions & 0 deletions xarray/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down