Skip to content

Commit 40505bb

Browse files
committed
BUG: Error upon Series.Groupby.nunique with empty Series (pandas-dev#12553)
Modified tests simplify tests Add whatsnew Moved len check
1 parent 1b0333b commit 40505bb

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

doc/source/whatsnew/v0.19.2.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ Bug Fixes
5757
- Bug in resampling a ``DatetimeIndex`` in local TZ, covering a DST change, which would raise ``AmbiguousTimeError`` (:issue:`14682`)
5858

5959

60-
60+
- Bug in ``Series.groupby.nunique()`` raising an ``IndexError`` for an empty ``Series`` (:issue:`12553`)
6161

6262

6363

pandas/core/groupby.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -2898,6 +2898,7 @@ def true_and_notnull(x, *args, **kwargs):
28982898
def nunique(self, dropna=True):
28992899
""" Returns number of unique elements in the group """
29002900
ids, _, _ = self.grouper.group_info
2901+
29012902
val = self.obj.get_values()
29022903

29032904
try:
@@ -2928,7 +2929,10 @@ def nunique(self, dropna=True):
29282929
inc[idx] = 1
29292930

29302931
out = np.add.reduceat(inc, idx).astype('int64', copy=False)
2931-
res = out if ids[0] != -1 else out[1:]
2932+
if len(ids):
2933+
res = out if ids[0] != -1 else out[1:]
2934+
else:
2935+
res = out[1:]
29322936
ri = self.grouper.result_index
29332937

29342938
# we might have duplications among the bins

pandas/tests/test_groupby.py

+7
Original file line numberDiff line numberDiff line change
@@ -6754,6 +6754,13 @@ def test_nunique_with_object(self):
67546754
expected = pd.Series([1] * 5, name='name', index=index)
67556755
tm.assert_series_equal(result, expected)
67566756

6757+
def test_nunique_with_empty_series(self):
6758+
# GH 12553
6759+
data = pd.Series(name='name')
6760+
result = data.groupby(level=0).nunique()
6761+
expected = pd.Series(name='name', dtype='int64')
6762+
tm.assert_series_equal(result, expected)
6763+
67576764
def test_transform_with_non_scalar_group(self):
67586765
# GH 10165
67596766
cols = pd.MultiIndex.from_tuples([

0 commit comments

Comments
 (0)