Skip to content

REF: simplify Index.astype #41703

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 2 commits into from
May 31, 2021
Merged
Show file tree
Hide file tree
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
11 changes: 4 additions & 7 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -906,13 +906,10 @@ def astype(self, dtype, copy=True):
if is_dtype_equal(self.dtype, dtype):
return self.copy() if copy else self

elif is_categorical_dtype(dtype):
from pandas.core.indexes.category import CategoricalIndex

return CategoricalIndex(self, name=self.name, dtype=dtype, copy=copy)

elif is_extension_array_dtype(dtype):
return Index(np.asarray(self), name=self.name, dtype=dtype, copy=copy)
elif isinstance(dtype, ExtensionDtype):
cls = dtype.construct_array_type()
new_values = cls._from_sequence(self, dtype=dtype, copy=False)
return Index(new_values, dtype=dtype, copy=copy, name=self.name)

try:
casted = self._values.astype(dtype, copy=copy)
Expand Down
13 changes: 10 additions & 3 deletions pandas/core/indexes/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
cache_readonly,
doc,
)
from pandas.util._exceptions import rewrite_exception

from pandas.core.dtypes.cast import (
find_common_type,
Expand Down Expand Up @@ -365,11 +366,17 @@ def astype(self, dtype, copy: bool = True) -> Index:
return self
return self.copy()

if isinstance(dtype, np.dtype) and dtype.kind == "M" and dtype != "M8[ns]":
if (
isinstance(self.dtype, np.dtype)
and isinstance(dtype, np.dtype)
and dtype.kind == "M"
and dtype != "M8[ns]"
):
# For now Datetime supports this by unwrapping ndarray, but DTI doesn't
raise TypeError(f"Cannot cast {type(self._data).__name__} to dtype")
raise TypeError(f"Cannot cast {type(self).__name__} to dtype")

new_values = self._data.astype(dtype, copy=copy)
with rewrite_exception(type(self._data).__name__, type(self).__name__):
new_values = self._data.astype(dtype, copy=copy)

# pass copy=False because any copying will be done in the
# _data.astype call above
Expand Down
6 changes: 0 additions & 6 deletions pandas/core/indexes/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,12 +422,6 @@ def __reduce__(self):
d.update(self._get_attributes_dict())
return _new_IntervalIndex, (type(self), d), None

@Appender(Index.astype.__doc__)
def astype(self, dtype, copy: bool = True):
with rewrite_exception("IntervalArray", type(self).__name__):
new_values = self._values.astype(dtype, copy=copy)
return Index(new_values, dtype=new_values.dtype, name=self.name)

@property
def inferred_type(self) -> str:
"""Return a string of the type inferred from the values"""
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/datetimes/methods/test_astype.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ def test_astype_object_with_nat(self):
def test_astype_raises(self, dtype):
# GH 13149, GH 13209
idx = DatetimeIndex(["2016-05-16", "NaT", NaT, np.NaN])
msg = "Cannot cast DatetimeArray to dtype"
msg = "Cannot cast DatetimeIndex to dtype"
with pytest.raises(TypeError, match=msg):
idx.astype(dtype)

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/period/methods/test_astype.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class TestPeriodIndexAsType:
def test_astype_raises(self, dtype):
# GH#13149, GH#13209
idx = PeriodIndex(["2016-05-16", "NaT", NaT, np.NaN], freq="D")
msg = "Cannot cast PeriodArray to dtype"
msg = "Cannot cast PeriodIndex to dtype"
with pytest.raises(TypeError, match=msg):
idx.astype(dtype)

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/period/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,7 @@ def setup_method(self, method):
self.series = Series(period_range("2000-01-01", periods=10, freq="D"))

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

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/timedeltas/methods/test_astype.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def test_astype_timedelta64(self):
def test_astype_raises(self, dtype):
# GH 13149, GH 13209
idx = TimedeltaIndex([1e14, "NaT", NaT, np.NaN])
msg = "Cannot cast TimedeltaArray to dtype"
msg = "Cannot cast TimedeltaIndex to dtype"
with pytest.raises(TypeError, match=msg):
idx.astype(dtype)

Expand Down