Skip to content

Commit ef349ca

Browse files
authored
REF: avoid special-casing Categorical astype (#38530)
1 parent 5a172c5 commit ef349ca

File tree

3 files changed

+8
-18
lines changed

3 files changed

+8
-18
lines changed

pandas/core/indexes/category.py

-5
Original file line numberDiff line numberDiff line change
@@ -354,11 +354,6 @@ def __contains__(self, key: Any) -> bool:
354354

355355
return contains(self, key, container=self._engine)
356356

357-
@doc(Index.astype)
358-
def astype(self, dtype, copy=True):
359-
res_data = self._data.astype(dtype, copy=copy)
360-
return Index(res_data, name=self.name)
361-
362357
@doc(Index.fillna)
363358
def fillna(self, value, downcast=None):
364359
value = self._require_scalar(value)

pandas/core/indexes/extension.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from pandas.errors import AbstractMethodError
1212
from pandas.util._decorators import cache_readonly, doc
1313

14-
from pandas.core.dtypes.common import is_dtype_equal, is_object_dtype
14+
from pandas.core.dtypes.common import is_dtype_equal, is_object_dtype, pandas_dtype
1515
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
1616

1717
from pandas.core.arrays import ExtensionArray
@@ -294,9 +294,12 @@ def map(self, mapper, na_action=None):
294294

295295
@doc(Index.astype)
296296
def astype(self, dtype, copy=True):
297-
if is_dtype_equal(self.dtype, dtype) and copy is False:
298-
# Ensure that self.astype(self.dtype) is self
299-
return self
297+
dtype = pandas_dtype(dtype)
298+
if is_dtype_equal(self.dtype, dtype):
299+
if not copy:
300+
# Ensure that self.astype(self.dtype) is self
301+
return self
302+
return self.copy()
300303

301304
new_values = self._data.astype(dtype, copy=copy)
302305

pandas/core/internals/blocks.py

+1-9
Original file line numberDiff line numberDiff line change
@@ -649,15 +649,7 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
649649
def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike:
650650
values = self.values
651651

652-
if is_categorical_dtype(dtype):
653-
654-
if is_categorical_dtype(values.dtype):
655-
# GH#10696/GH#18593: update an existing categorical efficiently
656-
return values.astype(dtype, copy=copy)
657-
658-
return Categorical(values, dtype=dtype)
659-
660-
elif is_datetime64tz_dtype(dtype) and is_datetime64_dtype(values.dtype):
652+
if is_datetime64tz_dtype(dtype) and is_datetime64_dtype(values.dtype):
661653
# if we are passed a datetime64[ns, tz]
662654
if copy:
663655
# this should be the only copy

0 commit comments

Comments
 (0)