Skip to content

Commit 23ce980

Browse files
Merge pull request #11639 from jorisvandenbossche/cat-remove-unused
BUG: remove_unused_categories with NaN values (GH11599)
2 parents d6a7700 + c5ad19a commit 23ce980

File tree

3 files changed

+9
-0
lines changed

3 files changed

+9
-0
lines changed

doc/source/whatsnew/v0.17.1.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,3 +188,4 @@ Bug Fixes
188188
- Bug in ``DataFrame.join()`` with ``how='right'`` producing a ``TypeError`` (:issue:`11519`)
189189
- Bug in ``Series.quantile`` with empty list results has ``Index`` with ``object`` dtype (:issue:`11588`)
190190
- Bug in ``pd.merge`` results in empty ``Int64Index`` rather than ``Index(dtype=object)`` when the merge result is empty (:issue:`11588`)
191+
- Bug in ``remove_unused_categories`` when having ``NaN`` values (:issue:`11599`).

pandas/core/categorical.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -817,6 +817,9 @@ def remove_unused_categories(self, inplace=False):
817817
"""
818818
cat = self if inplace else self.copy()
819819
_used = sorted(np.unique(cat._codes))
820+
if _used[0] == -1:
821+
_used = _used[1:]
822+
820823
new_categories = cat.categories.take(_ensure_platform_int(_used))
821824

822825
from pandas.core.index import _ensure_index

pandas/tests/test_categorical.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -844,6 +844,11 @@ def test_remove_unused_categories(self):
844844
self.assert_numpy_array_equal(c.categories, exp_categories_dropped)
845845
self.assertIsNone(res)
846846

847+
# with NaN values (GH11599)
848+
c = Categorical(["a","b","c",np.nan], categories=["a","b","c","d","e"])
849+
res = c.remove_unused_categories()
850+
self.assert_numpy_array_equal(res.categories, np.array(["a","b","c"]))
851+
self.assert_numpy_array_equal(c.categories, exp_categories_all)
847852

848853
def test_nan_handling(self):
849854

0 commit comments

Comments
 (0)