Skip to content

Commit 1d7bcbd

Browse files
BUG: fix+test groupby on empty DataArray raises StopIteration (#3156)
* BUG: groupby on empty DataArray raises StopIteration Using groupby on an empty DataArray or Dataset raises StopIteration. It should raise a more meaningful error. Resolves: 3037 * BUG: groupby on empty DataArray Adding the name of the group to the error message. Making the message more user friendly * DOC: update whats-new.rst include bug: #3037 fix * Update doc/whats-new.rst Co-Authored-By: Maximilian Roos <[email protected]>
1 parent 77a31e5 commit 1d7bcbd

File tree

3 files changed

+13
-0
lines changed

3 files changed

+13
-0
lines changed

doc/whats-new.rst

+2
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,8 @@ Bug fixes
8383
- Fix HDF5 error that could arise when reading multiple groups from a file at
8484
once (:issue:`2954`).
8585
By `Stephan Hoyer <https://github.com/shoyer>`_.
86+
- Better error message when using groupby on an empty DataArray (:issue:`3037`).
87+
By `Hasan Ahmad <https://github.com/HasanAhmadQ7>`_.
8688

8789
.. _whats-new.0.12.2:
8890

xarray/core/groupby.py

+3
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,9 @@ def __init__(self, obj, group, squeeze=False, grouper=None, bins=None,
232232
raise TypeError('`group` must be an xarray.DataArray or the '
233233
'name of an xarray variable or dimension')
234234
group = obj[group]
235+
if len(group) == 0:
236+
raise ValueError("{} must not be empty".format(group.name))
237+
235238
if group.name not in obj.coords and group.name in obj.dims:
236239
# DummyGroups should not appear on groupby results
237240
group = _DummyGroup(obj, group.name, group.coords)

xarray/tests/test_groupby.py

+8
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,14 @@ def func(arg1, arg2, arg3=0):
105105
assert_identical(expected, actual)
106106

107107

108+
def test_da_groupby_empty():
109+
110+
empty_array = xr.DataArray([], dims='dim')
111+
112+
with pytest.raises(ValueError):
113+
empty_array.groupby('dim')
114+
115+
108116
def test_da_groupby_quantile():
109117

110118
array = xr.DataArray([1, 2, 3, 4, 5, 6],

0 commit comments

Comments
 (0)