Skip to content

BUG: avoid unnecessary casting in CategoricalIndex.reindex #42063

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 9 commits into from
Jul 12, 2021
13 changes: 6 additions & 7 deletions pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,9 +399,9 @@ def reindex(
indexer = None
missing = np.array([], dtype=np.intp)
else:
indexer, missing = self.get_indexer_non_unique(np.array(target))
indexer, missing = self.get_indexer_non_unique(target)

if len(self.codes) and indexer is not None:
if len(self) and indexer is not None:
new_target = self.take(indexer)
else:
new_target = target
Expand All @@ -410,10 +410,8 @@ def reindex(
if len(missing):
cats = self.categories.get_indexer(target)

if not isinstance(cats, CategoricalIndex) or (cats == -1).any():
# coerce to a regular index here!
result = Index(np.array(self), name=self.name)
new_target, indexer, _ = result._reindex_non_unique(target)
if not isinstance(target, CategoricalIndex) or (cats == -1).any():
new_target, indexer, _ = super()._reindex_non_unique(target)
else:

codes = new_target.codes.copy()
Expand All @@ -426,11 +424,12 @@ def reindex(
# coerce based on the actual values, only on the dtype)
# unless we had an initial Categorical to begin with
# in which case we are going to conform to the passed Categorical
new_target = np.asarray(new_target)
if is_categorical_dtype(target):
cat = Categorical(new_target, dtype=target.dtype)
new_target = type(self)._simple_new(cat, name=self.name)
else:
# e.g. test_reindex_with_categoricalindex, test_reindex_duplicate_target
new_target = np.asarray(new_target)
new_target = Index(new_target, name=self.name)

return new_target, indexer
Expand Down