Skip to content

BUG: min/max on empty categorical fails #30227

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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,7 @@ Categorical
same type as if one used the :meth:`.str.` / :meth:`.dt.` on a :class:`Series` of that type. E.g. when accessing :meth:`Series.dt.tz_localize` on a
:class:`Categorical` with duplicate entries, the accessor was skipping duplicates (:issue:`27952`)
- Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` that would give incorrect results on categorical data (:issue:`26988`)
- Bug where calling :meth:`Categorical.min` or :meth:`Categorical.max` on an empty Categorical would raise a numpy exception.


Datetimelike
Expand Down
8 changes: 8 additions & 0 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -2126,6 +2126,10 @@ def min(self, skipna=True):
min : the minimum of this `Categorical`
"""
self.check_for_ordered("min")

if len(self._codes) == 0:
return np.nan

good = self._codes != -1
if not good.all():
if skipna:
Expand Down Expand Up @@ -2153,6 +2157,10 @@ def max(self, skipna=True):
max : the maximum of this `Categorical`
"""
self.check_for_ordered("max")

if len(self._codes) == 0:
return np.nan

good = self._codes != -1
if not good.all():
if skipna:
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/reductions/test_reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1060,6 +1060,12 @@ def test_min_max_skipna(self, skipna):
assert np.isnan(_min)
assert np.isnan(_max)

def test_min_max_empty(self):
cat = Series(Categorical([], categories=list("ABC"), ordered=True))

assert isna(cat.min())
assert isna(cat.max())


class TestSeriesMode:
# Note: the name TestSeriesMode indicates these tests
Expand Down