|
49 | 49 | validate_insert_loc,
|
50 | 50 | )
|
51 | 51 |
|
52 |
| -from pandas.core.dtypes.astype import astype_nansafe |
| 52 | +from pandas.core.dtypes.astype import ( |
| 53 | + astype_array, |
| 54 | + astype_nansafe, |
| 55 | +) |
53 | 56 | from pandas.core.dtypes.cast import (
|
54 | 57 | construct_1d_arraylike_from_scalar,
|
55 | 58 | find_common_type,
|
|
90 | 93 | from pandas.core.base import PandasObject
|
91 | 94 | import pandas.core.common as com
|
92 | 95 | from pandas.core.construction import (
|
| 96 | + ensure_wrapped_if_datetimelike, |
93 | 97 | extract_array,
|
94 | 98 | sanitize_array,
|
95 | 99 | )
|
@@ -120,8 +124,6 @@ class ellipsis(Enum):
|
120 | 124 |
|
121 | 125 | SparseIndexKind = Literal["integer", "block"]
|
122 | 126 |
|
123 |
| - from pandas.core.dtypes.dtypes import ExtensionDtype |
124 |
| - |
125 | 127 | from pandas import Series
|
126 | 128 |
|
127 | 129 | else:
|
@@ -1305,24 +1307,16 @@ def astype(self, dtype: AstypeArg | None = None, copy: bool = True):
|
1305 | 1307 | future_dtype = pandas_dtype(dtype)
|
1306 | 1308 | if not isinstance(future_dtype, SparseDtype):
|
1307 | 1309 | # GH#34457
|
1308 |
| - if isinstance(future_dtype, np.dtype): |
1309 |
| - values = np.array(self) |
1310 |
| - return astype_nansafe(values, dtype=future_dtype) |
1311 |
| - else: |
1312 |
| - # pylint: disable-next=used-before-assignment |
1313 |
| - dtype = cast(ExtensionDtype, dtype) |
1314 |
| - cls = dtype.construct_array_type() |
1315 |
| - return cls._from_sequence(self, dtype=dtype, copy=copy) |
| 1310 | + values = np.asarray(self) |
| 1311 | + values = ensure_wrapped_if_datetimelike(values) |
| 1312 | + return astype_array(values, dtype=future_dtype, copy=False) |
1316 | 1313 |
|
1317 | 1314 | dtype = self.dtype.update_dtype(dtype)
|
1318 | 1315 | subtype = pandas_dtype(dtype._subtype_with_str)
|
| 1316 | + subtype = cast(np.dtype, subtype) # ensured by update_dtype |
1319 | 1317 | sp_values = astype_nansafe(self.sp_values, subtype, copy=copy)
|
1320 | 1318 |
|
1321 |
| - # error: Argument 1 to "_simple_new" of "SparseArray" has incompatible type |
1322 |
| - # "ExtensionArray"; expected "ndarray" |
1323 |
| - return self._simple_new( |
1324 |
| - sp_values, self.sp_index, dtype # type: ignore[arg-type] |
1325 |
| - ) |
| 1319 | + return self._simple_new(sp_values, self.sp_index, dtype) |
1326 | 1320 |
|
1327 | 1321 | def map(self: SparseArrayT, mapper) -> SparseArrayT:
|
1328 | 1322 | """
|
|
0 commit comments