diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 57dd1d05a274e..719b5b5433f9c 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -170,7 +170,7 @@ Bug fixes Categorical ^^^^^^^^^^^ -- +- Bug in ``CategoricalIndex.reindex`` failed when ``Index`` passed with elements all in category (:issue:`28690`) - Datetimelike diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index e2a7752cf3f0d..bd9224d340ec8 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -441,7 +441,7 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None): if len(missing): cats = self.categories.get_indexer(target) - if (cats == -1).any(): + 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(np.array(target)) diff --git a/pandas/tests/indexes/categorical/test_reindex.py b/pandas/tests/indexes/categorical/test_reindex.py index 668c559abd08e..8228c5139ccdd 100644 --- a/pandas/tests/indexes/categorical/test_reindex.py +++ b/pandas/tests/indexes/categorical/test_reindex.py @@ -1,7 +1,7 @@ import numpy as np import pytest -from pandas import Categorical, CategoricalIndex, Index, Series +from pandas import Categorical, CategoricalIndex, DataFrame, Index, Series import pandas._testing as tm @@ -59,3 +59,35 @@ def test_reindex_missing_category(self): msg = "'fill_value=-1' is not present in this Categorical's categories" with pytest.raises(TypeError, match=msg): ser.reindex([1, 2, 3, 4, 5], fill_value=-1) + + @pytest.mark.parametrize( + "index_df,index_res,index_exp", + [ + ( + CategoricalIndex([], categories=["A"]), + Index(["A"]), + Index(["A"]), + ), + ( + CategoricalIndex([], categories=["A"]), + Index(["B"]), + Index(["B"]), + ), + ( + CategoricalIndex([], categories=["A"]), + CategoricalIndex(["A"]), + CategoricalIndex(["A"]), + ), + ( + CategoricalIndex([], categories=["A"]), + CategoricalIndex(["B"]), + CategoricalIndex(["B"]), + ), + ], + ) + def test_reindex_not_category(self, index_df, index_res, index_exp): + # GH: 28690 + df = DataFrame(index=index_df) + result = df.reindex(index=index_res) + expected = DataFrame(index=index_exp) + tm.assert_frame_equal(result, expected)