|
40 | 40 | DtypeObj,
|
41 | 41 | Scalar,
|
42 | 42 | )
|
| 43 | +from pandas.errors import IntCastingNaNError |
43 | 44 | from pandas.util._exceptions import find_stack_level
|
44 | 45 | from pandas.util._validators import validate_bool_kwarg
|
45 | 46 |
|
@@ -1167,9 +1168,7 @@ def astype_nansafe(
|
1167 | 1168 | raise TypeError(f"cannot astype a timedelta from [{arr.dtype}] to [{dtype}]")
|
1168 | 1169 |
|
1169 | 1170 | elif np.issubdtype(arr.dtype, np.floating) and np.issubdtype(dtype, np.integer):
|
1170 |
| - |
1171 |
| - if not np.isfinite(arr).all(): |
1172 |
| - raise ValueError("Cannot convert non-finite values (NA or inf) to integer") |
| 1171 | + return astype_float_to_int_nansafe(arr, dtype, copy) |
1173 | 1172 |
|
1174 | 1173 | elif is_object_dtype(arr):
|
1175 | 1174 |
|
@@ -1207,6 +1206,19 @@ def astype_nansafe(
|
1207 | 1206 | return arr.astype(dtype, copy=copy)
|
1208 | 1207 |
|
1209 | 1208 |
|
| 1209 | +def astype_float_to_int_nansafe( |
| 1210 | + values: np.ndarray, dtype: np.dtype, copy: bool |
| 1211 | +) -> np.ndarray: |
| 1212 | + """ |
| 1213 | + astype with a check preventing converting NaN to an meaningless integer value. |
| 1214 | + """ |
| 1215 | + if not np.isfinite(values).all(): |
| 1216 | + raise IntCastingNaNError( |
| 1217 | + "Cannot convert non-finite values (NA or inf) to integer" |
| 1218 | + ) |
| 1219 | + return values.astype(dtype, copy=copy) |
| 1220 | + |
| 1221 | + |
1210 | 1222 | def astype_array(values: ArrayLike, dtype: DtypeObj, copy: bool = False) -> ArrayLike:
|
1211 | 1223 | """
|
1212 | 1224 | Cast array (ndarray or ExtensionArray) to the new dtype.
|
@@ -1946,6 +1958,17 @@ def construct_1d_ndarray_preserving_na(
|
1946 | 1958 | ):
|
1947 | 1959 | # TODO(numpy#12550): special-case can be removed
|
1948 | 1960 | subarr = construct_1d_object_array_from_listlike(list(values))
|
| 1961 | + elif ( |
| 1962 | + dtype is not None |
| 1963 | + and dtype.kind in ["i", "u"] |
| 1964 | + and isinstance(values, np.ndarray) |
| 1965 | + and values.dtype.kind == "f" |
| 1966 | + ): |
| 1967 | + # Argument 2 to "astype_float_to_int_nansafe" has incompatible |
| 1968 | + # type "Union[dtype[Any], ExtensionDtype]"; expected "dtype[Any]" |
| 1969 | + return astype_float_to_int_nansafe( |
| 1970 | + values, dtype, copy=copy # type: ignore[arg-type] |
| 1971 | + ) |
1949 | 1972 | else:
|
1950 | 1973 | # error: Argument "dtype" to "array" has incompatible type
|
1951 | 1974 | # "Union[dtype[Any], ExtensionDtype, None]"; expected "Union[dtype[Any],
|
|
0 commit comments