Skip to content

Commit 7d02fa5

Browse files
jbrockmendelroberthdevries
authored andcommitted
REF: standardize CategoricalIndex._shallow_copy usage (pandas-dev#32141)
1 parent d4bd051 commit 7d02fa5

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

pandas/core/indexes/category.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -264,10 +264,14 @@ def _simple_new(cls, values, name=None, dtype=None):
264264
# --------------------------------------------------------------------
265265

266266
@Appender(Index._shallow_copy.__doc__)
267-
def _shallow_copy(self, values=None, dtype=None, **kwargs):
268-
if dtype is None:
269-
dtype = self.dtype
270-
return super()._shallow_copy(values=values, dtype=dtype, **kwargs)
267+
def _shallow_copy(self, values=None, **kwargs):
268+
if values is None:
269+
values = self.values
270+
271+
cat = Categorical(values, dtype=self.dtype)
272+
273+
name = kwargs.get("name", self.name)
274+
return type(self)._simple_new(cat, name=name)
271275

272276
def _is_dtype_compat(self, other) -> bool:
273277
"""
@@ -422,9 +426,9 @@ def unique(self, level=None):
422426
if level is not None:
423427
self._validate_index_level(level)
424428
result = self.values.unique()
425-
# CategoricalIndex._shallow_copy keeps original dtype
426-
# if not otherwise specified
427-
return self._shallow_copy(result, dtype=result.dtype)
429+
# Use _simple_new instead of _shallow_copy to ensure we keep dtype
430+
# of result, not self.
431+
return type(self)._simple_new(result, name=self.name)
428432

429433
@Appender(Index.duplicated.__doc__)
430434
def duplicated(self, keep="first"):
@@ -450,7 +454,7 @@ def where(self, cond, other=None):
450454
other = self._na_value
451455
values = np.where(cond, self.values, other)
452456
cat = Categorical(values, dtype=self.dtype)
453-
return self._shallow_copy(cat, **self._get_attributes_dict())
457+
return self._shallow_copy(cat)
454458

455459
def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
456460
"""

0 commit comments

Comments
 (0)