Skip to content
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
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ Deprecations

Bug fixes
~~~~~~~~~
- Fix :py:class:`~xarray.groupers.BinGrouper` when ``labels`` is not specified (:issue:`10284`).
By `Deepak Cherian <https://github.com/dcherian>`_.

- Allow accessing arbitrary attributes on Pandas ExtensionArrays.
By `Deepak Cherian <https://github.com/dcherian>`_.
Expand Down
2 changes: 1 addition & 1 deletion xarray/groupers.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ def factorize(self, group: T_Group) -> EncodedGroups:
# This seems silly, but it lets us have Pandas handle the complexity
# of `labels`, `precision`, and `include_lowest`, even when group is a chunked array
# Pandas ignores labels when IntervalIndex is passed
if not isinstance(self.bins, pd.IntervalIndex):
if self.labels is None or not isinstance(self.bins, pd.IntervalIndex):
dummy, _ = self._cut(np.array([0]).astype(group.dtype))
full_index = dummy.categories
else:
Expand Down
16 changes: 11 additions & 5 deletions xarray/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1042,10 +1042,12 @@ def test_groupby_math_bitshift() -> None:
assert_equal(right_expected, right_actual)


@pytest.mark.parametrize(
"x_bins", ((0, 2, 4, 6), pd.IntervalIndex.from_breaks((0, 2, 4, 6), closed="left"))
)
@pytest.mark.parametrize("use_flox", [True, False])
def test_groupby_bins_cut_kwargs(use_flox: bool) -> None:
def test_groupby_bins_cut_kwargs(use_flox: bool, x_bins) -> None:
da = xr.DataArray(np.arange(12).reshape(6, 2), dims=("x", "y"))
x_bins = (0, 2, 4, 6)

with xr.set_options(use_flox=use_flox):
actual = da.groupby_bins(
Expand All @@ -1055,7 +1057,12 @@ def test_groupby_bins_cut_kwargs(use_flox: bool) -> None:
np.array([[1.0, 2.0], [5.0, 6.0], [9.0, 10.0]]),
dims=("x_bins", "y"),
coords={
"x_bins": ("x_bins", pd.IntervalIndex.from_breaks(x_bins, closed="left"))
"x_bins": (
"x_bins",
x_bins
if isinstance(x_bins, pd.IntervalIndex)
else pd.IntervalIndex.from_breaks(x_bins, closed="left"),
)
},
)
assert_identical(expected, actual)
Expand All @@ -1067,9 +1074,8 @@ def test_groupby_bins_cut_kwargs(use_flox: bool) -> None:
assert_identical(expected, actual)

with xr.set_options(use_flox=use_flox):
bins_index = pd.IntervalIndex.from_breaks(x_bins)
labels = ["one", "two", "three"]
actual = da.groupby(x=BinGrouper(bins=bins_index, labels=labels)).sum()
actual = da.groupby(x=BinGrouper(bins=x_bins, labels=labels)).sum()
assert actual.xindexes["x_bins"].index.equals(pd.Index(labels)) # type: ignore[attr-defined]


Expand Down
Loading