Skip to content

Commit ed12ad0

Browse files
committed
BUG: Error upon Series.Groupby.nunique with empty Series (pandas-dev#12553)
Modified tests simplify tests Add whatsnew
1 parent 423c16a commit ed12ad0

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

doc/source/whatsnew/v0.19.2.txt

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

5858

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

6161

6262

pandas/core/groupby.py

+4
Original file line numberDiff line numberDiff line change
@@ -2898,6 +2898,10 @@ 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+
2902+
if len(ids) == 0:
2903+
return Series(index=self.dtype.index, name=self.name)
2904+
29012905
val = self.obj.get_values()
29022906

29032907
try:

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')
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)