Skip to content

Commit f7c4694

Browse files
committed
Avoid copying categoricals
1 parent 36b8f20 commit f7c4694

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

pandas/core/arrays/categorical.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -575,7 +575,7 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
575575
# GH 10696/18593/18630
576576
dtype = self.dtype.update_dtype(dtype)
577577
self = self.copy() if copy else self
578-
result = self._set_dtype(dtype)
578+
result = self._set_dtype(dtype, copy=False)
579579

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

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

948-
def _set_dtype(self, dtype: CategoricalDtype) -> Self:
948+
def _set_dtype(self, dtype: CategoricalDtype, copy: bool = True) -> Self:
949949
"""
950950
Internal method for directly updating the CategoricalDtype
951951
@@ -958,7 +958,9 @@ def _set_dtype(self, dtype: CategoricalDtype) -> Self:
958958
We don't do any validation here. It's assumed that the dtype is
959959
a (valid) instance of `CategoricalDtype`.
960960
"""
961-
codes = recode_for_categories(self.codes, self.categories, dtype.categories)
961+
codes = recode_for_categories(
962+
self.codes, self.categories, dtype.categories, copy
963+
)
962964
return type(self)._simple_new(codes, dtype=dtype)
963965

964966
def set_ordered(self, value: bool) -> Self:

0 commit comments

Comments
 (0)