|
33 | 33 | from pandas.util._decorators import Appender, cache_readonly, doc |
34 | 34 |
|
35 | 35 | from pandas.core.dtypes.cast import ( |
| 36 | + astype_nansafe, |
36 | 37 | find_common_type, |
37 | 38 | maybe_cast_to_integer_array, |
38 | 39 | maybe_promote, |
@@ -693,22 +694,21 @@ def astype(self, dtype, copy=True): |
693 | 694 | if is_dtype_equal(self.dtype, dtype): |
694 | 695 | return self.copy() if copy else self |
695 | 696 |
|
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 |
| 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" |
701 | 703 | ) |
702 | 704 |
|
703 | | - elif is_extension_array_dtype(dtype): |
704 | | - return Index(np.asarray(self), name=self.name, dtype=dtype, copy=copy) |
705 | | - |
706 | 705 | try: |
707 | | - casted = self._values.astype(dtype, copy=copy) |
708 | | - except (TypeError, ValueError) as err: |
| 706 | + casted = astype_nansafe(self._values, dtype=dtype, copy=True) |
| 707 | + except TypeError as err: |
709 | 708 | raise TypeError( |
710 | 709 | f"Cannot cast {type(self).__name__} to dtype {dtype}" |
711 | 710 | ) from err |
| 711 | + |
712 | 712 | return Index(casted, name=self.name, dtype=dtype) |
713 | 713 |
|
714 | 714 | _index_shared_docs[ |
|
0 commit comments