Skip to content

BinGrouper: reduce indirection #10270

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

Merged
merged 1 commit into from
Apr 29, 2025
Merged
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
23 changes: 13 additions & 10 deletions xarray/groupers.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,15 +365,12 @@ def _cut(self, data):
retbins=True,
)

def _factorize_lazy(self, group: T_Group) -> DataArray:
def _wrapper(data, **kwargs):
binned, bins = self._cut(data)
if isinstance(self.bins, int):
# we are running eagerly, update self.bins with actual edges instead
self.bins = bins
return binned.codes.reshape(data.shape)

return apply_ufunc(_wrapper, group, dask="parallelized", keep_attrs=True)
def _pandas_cut_wrapper(self, data, **kwargs):
binned, bins = self._cut(data)
if isinstance(self.bins, int):
# we are running eagerly, update self.bins with actual edges instead
self.bins = bins
return binned.codes.reshape(data.shape)

def factorize(self, group: T_Group) -> EncodedGroups:
if isinstance(group, _DummyGroup):
Expand All @@ -383,7 +380,13 @@ def factorize(self, group: T_Group) -> EncodedGroups:
raise ValueError(
f"Bin edges must be provided when grouping by chunked arrays. Received {self.bins=!r} instead"
)
codes = self._factorize_lazy(group)
codes = apply_ufunc(
self._pandas_cut_wrapper,
group,
dask="parallelized",
keep_attrs=True,
output_dtypes=[np.int64],
)
if not by_is_chunked and array_all(codes == -1):
raise ValueError(
f"None of the data falls within bins with edges {self.bins!r}"
Expand Down
Loading