Skip to content

Commit 2544c3a

Browse files
Backport PR #33513 on branch 1.0.x (BUG: Fix Categorical.min / max bug) (#34022)
Co-authored-by: Daniel Saxton <[email protected]>
1 parent 8923fd2 commit 2544c3a

File tree

3 files changed

+11
-2
lines changed

3 files changed

+11
-2
lines changed

doc/source/whatsnew/v1.0.4.rst

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ Fixed regressions
2020
- Bug in DataFrame reductions using ``numeric_only=True`` and ExtensionArrays (:issue:`33256`).
2121
- Fix performance regression in ``memory_usage(deep=True)`` for object dtype (:issue:`33012`)
2222
- Bug where :meth:`Categorical.replace` would replace with ``NaN`` whenever the new value and replacement value were equal (:issue:`33288`)
23+
- Bug where an ordered :class:`Categorical` containing only ``NaN`` values would raise rather than returning ``NaN`` when taking the minimum or maximum (:issue:`33450`)
2324
-
2425

2526
.. _whatsnew_104.bug_fixes:

pandas/core/arrays/categorical.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2151,7 +2151,7 @@ def min(self, skipna=True):
21512151

21522152
good = self._codes != -1
21532153
if not good.all():
2154-
if skipna:
2154+
if skipna and good.any():
21552155
pointer = self._codes[good].min()
21562156
else:
21572157
return np.nan
@@ -2186,7 +2186,7 @@ def max(self, skipna=True):
21862186

21872187
good = self._codes != -1
21882188
if not good.all():
2189-
if skipna:
2189+
if skipna and good.any():
21902190
pointer = self._codes[good].max()
21912191
else:
21922192
return np.nan

pandas/tests/arrays/categorical/test_analytics.py

+8
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,14 @@ def test_min_max_with_nan(self, skipna):
8888
assert _min == 2
8989
assert _max == 1
9090

91+
@pytest.mark.parametrize("function", ["min", "max"])
92+
@pytest.mark.parametrize("skipna", [True, False])
93+
def test_min_max_only_nan(self, function, skipna):
94+
# https://github.com/pandas-dev/pandas/issues/33450
95+
cat = Categorical([np.nan], categories=[1, 2], ordered=True)
96+
result = getattr(cat, function)(skipna=skipna)
97+
assert result is np.nan
98+
9199
@pytest.mark.parametrize("method", ["min", "max"])
92100
def test_deprecate_numeric_only_min_max(self, method):
93101
# GH 25303

0 commit comments

Comments
 (0)