|
33 | 33 | from pandas.util._decorators import Appender, cache_readonly, doc
|
34 | 34 |
|
35 | 35 | from pandas.core.dtypes.cast import (
|
36 |
| - astype_nansafe, |
37 | 36 | find_common_type,
|
38 | 37 | maybe_cast_to_integer_array,
|
39 | 38 | maybe_promote,
|
@@ -694,21 +693,22 @@ def astype(self, dtype, copy=True):
|
694 | 693 | if is_dtype_equal(self.dtype, dtype):
|
695 | 694 | return self.copy() if copy else self
|
696 | 695 |
|
697 |
| - if needs_i8_conversion(dtype) and is_float_dtype(self.dtype): |
698 |
| - # We can't put this into astype_nansafe bc astype_nansafe allows |
699 |
| - # casting np.nan to NaT |
700 |
| - raise TypeError( |
701 |
| - f"Cannot convert {type(self).__name__} to dtype {dtype}; integer " |
702 |
| - "values are required for conversion" |
| 696 | + elif is_categorical_dtype(dtype): |
| 697 | + from pandas.core.indexes.category import CategoricalIndex |
| 698 | + |
| 699 | + return CategoricalIndex( |
| 700 | + self._values, name=self.name, dtype=dtype, copy=copy |
703 | 701 | )
|
704 | 702 |
|
| 703 | + elif is_extension_array_dtype(dtype): |
| 704 | + return Index(np.asarray(self), name=self.name, dtype=dtype, copy=copy) |
| 705 | + |
705 | 706 | try:
|
706 |
| - casted = astype_nansafe(self._values, dtype=dtype, copy=True) |
707 |
| - except TypeError as err: |
| 707 | + casted = self._values.astype(dtype, copy=copy) |
| 708 | + except (TypeError, ValueError) as err: |
708 | 709 | raise TypeError(
|
709 | 710 | f"Cannot cast {type(self).__name__} to dtype {dtype}"
|
710 | 711 | ) from err
|
711 |
| - |
712 | 712 | return Index(casted, name=self.name, dtype=dtype)
|
713 | 713 |
|
714 | 714 | _index_shared_docs[
|
|
0 commit comments