Skip to content

BUG: remove_unused_categories with NaN values (GH11599) #11639

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
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.17.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,4 @@ Bug Fixes
- Bug in ``DataFrame.join()`` with ``how='right'`` producing a ``TypeError`` (:issue:`11519`)
- Bug in ``Series.quantile`` with empty list results has ``Index`` with ``object`` dtype (:issue:`11588`)
- Bug in ``pd.merge`` results in empty ``Int64Index`` rather than ``Index(dtype=object)`` when the merge result is empty (:issue:`11588`)
- Bug in ``remove_unused_categories`` when having ``NaN`` values (:issue:`11599`).
3 changes: 3 additions & 0 deletions pandas/core/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,9 @@ def remove_unused_categories(self, inplace=False):
"""
cat = self if inplace else self.copy()
_used = sorted(np.unique(cat._codes))
if _used[0] == -1:
_used = _used[1:]

new_categories = cat.categories.take(_ensure_platform_int(_used))

from pandas.core.index import _ensure_index
Expand Down
5 changes: 5 additions & 0 deletions pandas/tests/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -844,6 +844,11 @@ def test_remove_unused_categories(self):
self.assert_numpy_array_equal(c.categories, exp_categories_dropped)
self.assertIsNone(res)

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

def test_nan_handling(self):

Expand Down