Skip to content

REF: standardize CategoricalIndex._shallow_copy usage #32141

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 1 commit into from
Feb 22, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,10 +264,14 @@ def _simple_new(cls, values, name=None, dtype=None):
# --------------------------------------------------------------------

@Appender(Index._shallow_copy.__doc__)
def _shallow_copy(self, values=None, dtype=None, **kwargs):
if dtype is None:
dtype = self.dtype
return super()._shallow_copy(values=values, dtype=dtype, **kwargs)
def _shallow_copy(self, values=None, **kwargs):
if values is None:
values = self.values

cat = Categorical(values, dtype=self.dtype)

name = kwargs.get("name", self.name)
return type(self)._simple_new(cat, name=name)

def _is_dtype_compat(self, other) -> bool:
"""
Expand Down Expand Up @@ -422,9 +426,9 @@ def unique(self, level=None):
if level is not None:
self._validate_index_level(level)
result = self.values.unique()
# CategoricalIndex._shallow_copy keeps original dtype
# if not otherwise specified
return self._shallow_copy(result, dtype=result.dtype)
# Use _simple_new instead of _shallow_copy to ensure we keep dtype
# of result, not self.
return type(self)._simple_new(result, name=self.name)

@Appender(Index.duplicated.__doc__)
def duplicated(self, keep="first"):
Expand All @@ -450,7 +454,7 @@ def where(self, cond, other=None):
other = self._na_value
values = np.where(cond, self.values, other)
cat = Categorical(values, dtype=self.dtype)
return self._shallow_copy(cat, **self._get_attributes_dict())
return self._shallow_copy(cat)

def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
"""
Expand Down