Skip to content

PERF: Don't create a CategoricalIndex._engine in __contains__ if categories are RangeIndex #59178

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 3 commits into from
Jul 22, 2024
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
9 changes: 7 additions & 2 deletions pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,8 +377,13 @@ def __contains__(self, key: Any) -> bool:
# if key is a NaN, check if any NaN is in self.
if is_valid_na_for_dtype(key, self.categories.dtype):
return self.hasnans

return contains(self, key, container=self._engine)
if self.categories._typ == "rangeindex":
container: Index | libindex.IndexEngine | libindex.ExtensionEngine = (
self.categories
)
else:
container = self._engine
return contains(self, key, container=container)

def reindex(
self, target, method=None, level=None, limit: int | None = None, tolerance=None
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/indexes/categorical/test_category.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,3 +392,10 @@ def test_remove_maintains_order(self):
["a", "b", np.nan, "d", "d", "a"], categories=list("dba"), ordered=True
),
)


def test_contains_rangeindex_categories_no_engine():
ci = CategoricalIndex(range(3))
assert 2 in ci
assert 5 not in ci
assert "_engine" not in ci._cache