Skip to content
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

PERF: improves performance in remove_unused_categories #11643

Closed
wants to merge 1 commit into from
Closed
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
14 changes: 6 additions & 8 deletions pandas/core/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -816,16 +816,14 @@ def remove_unused_categories(self, inplace=False):
set_categories
"""
cat = self if inplace else self.copy()
_used = sorted(np.unique(cat._codes))
if _used[0] == -1:
_used = _used[1:]
idx, inv = np.unique(cat._codes, return_inverse=True)

new_categories = cat.categories.take(_ensure_platform_int(_used))
if idx.size != 0 and idx[0] == -1: # na sentinel
idx, inv = idx[1:], inv - 1

cat._codes = inv
cat._categories = cat.categories.take(idx)

from pandas.core.index import _ensure_index
new_categories = _ensure_index(new_categories)
cat._codes = _get_codes_for_values(cat.__array__(), new_categories)
cat._categories = new_categories
if not inplace:
return cat

Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,21 @@ def test_remove_unused_categories(self):
self.assert_numpy_array_equal(res.categories, np.array(["a","b","c"]))
self.assert_numpy_array_equal(c.categories, exp_categories_all)

val = ['F', np.nan, 'D', 'B', 'D', 'F', np.nan]
cat = pd.Categorical(values=val, categories=list('ABCDEFG'))
out = cat.remove_unused_categories()
self.assert_numpy_array_equal(out.categories, ['B', 'D', 'F'])
self.assert_numpy_array_equal(out.codes, [ 2, -1, 1, 0, 1, 2, -1])
self.assertEqual(out.get_values().tolist(), val)

alpha = list('abcdefghijklmnopqrstuvwxyz')
val = np.random.choice(alpha[::2], 10000).astype('object')
val[np.random.choice(len(val), 100)] = np.nan

cat = pd.Categorical(values=val, categories=alpha)
out = cat.remove_unused_categories()
self.assertEqual(out.get_values().tolist(), val.tolist())

def test_nan_handling(self):

# Nans are represented as -1 in codes
Expand Down