Skip to content

Commit 9870859

Browse files
authored
BUG: avoid unnecessary casting in CategoricalIndex.reindex (#42063)
1 parent 9f55011 commit 9870859

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

pandas/core/indexes/category.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -399,9 +399,9 @@ def reindex(
399399
indexer = None
400400
missing = np.array([], dtype=np.intp)
401401
else:
402-
indexer, missing = self.get_indexer_non_unique(np.array(target))
402+
indexer, missing = self.get_indexer_non_unique(target)
403403

404-
if len(self.codes) and indexer is not None:
404+
if len(self) and indexer is not None:
405405
new_target = self.take(indexer)
406406
else:
407407
new_target = target
@@ -410,10 +410,8 @@ def reindex(
410410
if len(missing):
411411
cats = self.categories.get_indexer(target)
412412

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

419417
codes = new_target.codes.copy()
@@ -426,11 +424,12 @@ def reindex(
426424
# coerce based on the actual values, only on the dtype)
427425
# unless we had an initial Categorical to begin with
428426
# in which case we are going to conform to the passed Categorical
429-
new_target = np.asarray(new_target)
430427
if is_categorical_dtype(target):
431428
cat = Categorical(new_target, dtype=target.dtype)
432429
new_target = type(self)._simple_new(cat, name=self.name)
433430
else:
431+
# e.g. test_reindex_with_categoricalindex, test_reindex_duplicate_target
432+
new_target = np.asarray(new_target)
434433
new_target = Index(new_target, name=self.name)
435434

436435
return new_target, indexer

0 commit comments

Comments
 (0)