Skip to content

Commit fb4c5b8

Browse files
authored
REF: simplify Index.astype (#41703)
1 parent 4ed1bc2 commit fb4c5b8

File tree

7 files changed

+18
-20
lines changed

7 files changed

+18
-20
lines changed

pandas/core/indexes/base.py

+4-7
Original file line numberDiff line numberDiff line change
@@ -906,13 +906,10 @@ def astype(self, dtype, copy=True):
906906
if is_dtype_equal(self.dtype, dtype):
907907
return self.copy() if copy else self
908908

909-
elif is_categorical_dtype(dtype):
910-
from pandas.core.indexes.category import CategoricalIndex
911-
912-
return CategoricalIndex(self, name=self.name, dtype=dtype, copy=copy)
913-
914-
elif is_extension_array_dtype(dtype):
915-
return Index(np.asarray(self), name=self.name, dtype=dtype, copy=copy)
909+
elif isinstance(dtype, ExtensionDtype):
910+
cls = dtype.construct_array_type()
911+
new_values = cls._from_sequence(self, dtype=dtype, copy=False)
912+
return Index(new_values, dtype=dtype, copy=copy, name=self.name)
916913

917914
try:
918915
casted = self._values.astype(dtype, copy=copy)

pandas/core/indexes/extension.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
cache_readonly,
1919
doc,
2020
)
21+
from pandas.util._exceptions import rewrite_exception
2122

2223
from pandas.core.dtypes.cast import (
2324
find_common_type,
@@ -365,11 +366,17 @@ def astype(self, dtype, copy: bool = True) -> Index:
365366
return self
366367
return self.copy()
367368

368-
if isinstance(dtype, np.dtype) and dtype.kind == "M" and dtype != "M8[ns]":
369+
if (
370+
isinstance(self.dtype, np.dtype)
371+
and isinstance(dtype, np.dtype)
372+
and dtype.kind == "M"
373+
and dtype != "M8[ns]"
374+
):
369375
# For now Datetime supports this by unwrapping ndarray, but DTI doesn't
370-
raise TypeError(f"Cannot cast {type(self._data).__name__} to dtype")
376+
raise TypeError(f"Cannot cast {type(self).__name__} to dtype")
371377

372-
new_values = self._data.astype(dtype, copy=copy)
378+
with rewrite_exception(type(self._data).__name__, type(self).__name__):
379+
new_values = self._data.astype(dtype, copy=copy)
373380

374381
# pass copy=False because any copying will be done in the
375382
# _data.astype call above

pandas/core/indexes/interval.py

-6
Original file line numberDiff line numberDiff line change
@@ -422,12 +422,6 @@ def __reduce__(self):
422422
d.update(self._get_attributes_dict())
423423
return _new_IntervalIndex, (type(self), d), None
424424

425-
@Appender(Index.astype.__doc__)
426-
def astype(self, dtype, copy: bool = True):
427-
with rewrite_exception("IntervalArray", type(self).__name__):
428-
new_values = self._values.astype(dtype, copy=copy)
429-
return Index(new_values, dtype=new_values.dtype, name=self.name)
430-
431425
@property
432426
def inferred_type(self) -> str:
433427
"""Return a string of the type inferred from the values"""

pandas/tests/indexes/datetimes/methods/test_astype.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ def test_astype_object_with_nat(self):
223223
def test_astype_raises(self, dtype):
224224
# GH 13149, GH 13209
225225
idx = DatetimeIndex(["2016-05-16", "NaT", NaT, np.NaN])
226-
msg = "Cannot cast DatetimeArray to dtype"
226+
msg = "Cannot cast DatetimeIndex to dtype"
227227
with pytest.raises(TypeError, match=msg):
228228
idx.astype(dtype)
229229

pandas/tests/indexes/period/methods/test_astype.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ class TestPeriodIndexAsType:
2121
def test_astype_raises(self, dtype):
2222
# GH#13149, GH#13209
2323
idx = PeriodIndex(["2016-05-16", "NaT", NaT, np.NaN], freq="D")
24-
msg = "Cannot cast PeriodArray to dtype"
24+
msg = "Cannot cast PeriodIndex to dtype"
2525
with pytest.raises(TypeError, match=msg):
2626
idx.astype(dtype)
2727

pandas/tests/indexes/period/test_constructors.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -538,7 +538,7 @@ def setup_method(self, method):
538538
self.series = Series(period_range("2000-01-01", periods=10, freq="D"))
539539

540540
def test_constructor_cant_cast_period(self):
541-
msg = "Cannot cast PeriodArray to dtype float64"
541+
msg = "Cannot cast PeriodIndex to dtype float64"
542542
with pytest.raises(TypeError, match=msg):
543543
Series(period_range("2000-01-01", periods=10, freq="D"), dtype=float)
544544

pandas/tests/indexes/timedeltas/methods/test_astype.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def test_astype_timedelta64(self):
101101
def test_astype_raises(self, dtype):
102102
# GH 13149, GH 13209
103103
idx = TimedeltaIndex([1e14, "NaT", NaT, np.NaN])
104-
msg = "Cannot cast TimedeltaArray to dtype"
104+
msg = "Cannot cast TimedeltaIndex to dtype"
105105
with pytest.raises(TypeError, match=msg):
106106
idx.astype(dtype)
107107

0 commit comments

Comments
 (0)