Skip to content

Commit cbbf347

Browse files
authored
Fix regression with grouper object on an IndexVariable (#7920)
* Fix regression with grouper object on an IndexVariable * Early cast IndexVariable to DataArray to avoid issues with flox
1 parent 4156ce5 commit cbbf347

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

xarray/core/groupby.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,6 +626,7 @@ def _resolve_group(obj: T_Xarray, group: T_Group | Hashable) -> T_Group:
626626
(group_dim,) = group.dims
627627
if len(group) != obj.sizes[group_dim]:
628628
raise ValueError(error_msg)
629+
newgroup = DataArray(group)
629630

630631
else:
631632
if not hashable(group):

xarray/tests/test_groupby.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,18 @@ def test_groupby_input_mutation() -> None:
137137
assert_identical(array, array_copy) # should not modify inputs
138138

139139

140+
@pytest.mark.parametrize("use_flox", [True, False])
141+
def test_groupby_indexvariable(use_flox: bool) -> None:
142+
# regression test for GH7919
143+
array = xr.DataArray([1, 2, 3], [("x", [2, 2, 1])])
144+
iv = xr.IndexVariable(dims="x", data=pd.Index(array.x.values))
145+
with xr.set_options(use_flox=use_flox):
146+
actual = array.groupby(iv).sum()
147+
actual = array.groupby(iv).sum()
148+
expected = xr.DataArray([3, 3], [("x", [1, 2])])
149+
assert_identical(expected, actual)
150+
151+
140152
@pytest.mark.parametrize(
141153
"obj",
142154
[

0 commit comments

Comments
 (0)