Skip to content
Merged
Changes from 1 commit
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
8 changes: 5 additions & 3 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -575,7 +575,7 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
# GH 10696/18593/18630
dtype = self.dtype.update_dtype(dtype)
self = self.copy() if copy else self
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this line if we pass self._set_dtype(dtype, copy=copy)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wasn't entirely sure. The self.copy is also creating a new Categorical object which is desired, I assume.

result = self._set_dtype(dtype)
result = self._set_dtype(dtype, copy=False)

elif isinstance(dtype, ExtensionDtype):
return super().astype(dtype, copy=copy)
Expand Down Expand Up @@ -945,7 +945,7 @@ def _set_categories(self, categories, fastpath: bool = False) -> None:

super().__init__(self._ndarray, new_dtype)

def _set_dtype(self, dtype: CategoricalDtype) -> Self:
def _set_dtype(self, dtype: CategoricalDtype, copy: bool = True) -> Self:
"""
Internal method for directly updating the CategoricalDtype

Expand All @@ -958,7 +958,9 @@ def _set_dtype(self, dtype: CategoricalDtype) -> Self:
We don't do any validation here. It's assumed that the dtype is
a (valid) instance of `CategoricalDtype`.
"""
codes = recode_for_categories(self.codes, self.categories, dtype.categories)
codes = recode_for_categories(
self.codes, self.categories, dtype.categories, copy
)
return type(self)._simple_new(codes, dtype=dtype)

def set_ordered(self, value: bool) -> Self:
Expand Down
Loading