Skip to content

PERF: remove categories #51344

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 2 commits into from
Feb 13, 2023
Merged
Changes from 1 commit
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
6 changes: 4 additions & 2 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@
from pandas.core.dtypes.missing import (
is_valid_na_for_dtype,
isna,
notna,
)

from pandas.core import (
Expand Down Expand Up @@ -1135,14 +1134,17 @@ def remove_categories(self, removals):
[NaN, 'c', 'b', 'c', NaN]
Categories (2, object): ['b', 'c']
"""
from pandas import Index

if not is_list_like(removals):
removals = [removals]

removals = {x for x in set(removals) if notna(x)}
removals = Index(removals).dropna().unique()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't the other way round be faster? e.g. unique().dropna()?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. Its not measurable with that benchmark, but I swapped it anyway.

new_categories = self.dtype.categories.difference(removals)
not_included = removals.difference(self.dtype.categories)

if len(not_included) != 0:
not_included = set(not_included)
raise ValueError(f"removals must all be in old categories: {not_included}")

return self.set_categories(new_categories, ordered=self.ordered, rename=False)
Expand Down