Skip to content

Commit 04424b0

Browse files
authored
PERF: Don't create a CategoricalIndex._engine in __contains__ if categories are RangeIndex (pandas-dev#59178)
* PERF: Don't create a CategoricalIndex._engine in __contains__ if categories are RangeIndex * Fix typing
1 parent 8f737b3 commit 04424b0

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

pandas/core/indexes/category.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -377,8 +377,13 @@ def __contains__(self, key: Any) -> bool:
377377
# if key is a NaN, check if any NaN is in self.
378378
if is_valid_na_for_dtype(key, self.categories.dtype):
379379
return self.hasnans
380-
381-
return contains(self, key, container=self._engine)
380+
if self.categories._typ == "rangeindex":
381+
container: Index | libindex.IndexEngine | libindex.ExtensionEngine = (
382+
self.categories
383+
)
384+
else:
385+
container = self._engine
386+
return contains(self, key, container=container)
382387

383388
def reindex(
384389
self, target, method=None, level=None, limit: int | None = None, tolerance=None

pandas/tests/indexes/categorical/test_category.py

+7
Original file line numberDiff line numberDiff line change
@@ -395,3 +395,10 @@ def test_remove_maintains_order(self):
395395
["a", "b", np.nan, "d", "d", "a"], categories=list("dba"), ordered=True
396396
),
397397
)
398+
399+
400+
def test_contains_rangeindex_categories_no_engine():
401+
ci = CategoricalIndex(range(3))
402+
assert 2 in ci
403+
assert 5 not in ci
404+
assert "_engine" not in ci._cache

0 commit comments

Comments
 (0)