Skip to content

Commit 5468223

Browse files
authored
BUG: CategoricalIndex.reindex fails when Index passed with labels all in category (pandas-dev#38492)
1 parent fde8d33 commit 5468223

File tree

3 files changed

+35
-3
lines changed

3 files changed

+35
-3
lines changed

doc/source/whatsnew/v1.3.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ Bug fixes
170170
Categorical
171171
^^^^^^^^^^^
172172

173-
-
173+
- Bug in ``CategoricalIndex.reindex`` failed when ``Index`` passed with elements all in category (:issue:`28690`)
174174
-
175175

176176
Datetimelike

pandas/core/indexes/category.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,7 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
428428
if len(missing):
429429
cats = self.categories.get_indexer(target)
430430

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

pandas/tests/indexes/categorical/test_reindex.py

+33-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import numpy as np
22
import pytest
33

4-
from pandas import Categorical, CategoricalIndex, Index, Series
4+
from pandas import Categorical, CategoricalIndex, DataFrame, Index, Series
55
import pandas._testing as tm
66

77

@@ -59,3 +59,35 @@ def test_reindex_missing_category(self):
5959
msg = "'fill_value=-1' is not present in this Categorical's categories"
6060
with pytest.raises(TypeError, match=msg):
6161
ser.reindex([1, 2, 3, 4, 5], fill_value=-1)
62+
63+
@pytest.mark.parametrize(
64+
"index_df,index_res,index_exp",
65+
[
66+
(
67+
CategoricalIndex([], categories=["A"]),
68+
Index(["A"]),
69+
Index(["A"]),
70+
),
71+
(
72+
CategoricalIndex([], categories=["A"]),
73+
Index(["B"]),
74+
Index(["B"]),
75+
),
76+
(
77+
CategoricalIndex([], categories=["A"]),
78+
CategoricalIndex(["A"]),
79+
CategoricalIndex(["A"]),
80+
),
81+
(
82+
CategoricalIndex([], categories=["A"]),
83+
CategoricalIndex(["B"]),
84+
CategoricalIndex(["B"]),
85+
),
86+
],
87+
)
88+
def test_reindex_not_category(self, index_df, index_res, index_exp):
89+
# GH: 28690
90+
df = DataFrame(index=index_df)
91+
result = df.reindex(index=index_res)
92+
expected = DataFrame(index=index_exp)
93+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)