diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index d89a1e012d5f8..96921fe0311c0 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -285,7 +285,7 @@ Datetimelike Timedelta ^^^^^^^^^ -- +- Bug in :func:`astype_nansafe` astype("timedelta64[ns]") fails when np.nan is included (:issue:`45798`) Time Zones ^^^^^^^^^^ diff --git a/pandas/core/dtypes/astype.py b/pandas/core/dtypes/astype.py index 1e78bf0cd33ae..daae491b09c8a 100644 --- a/pandas/core/dtypes/astype.py +++ b/pandas/core/dtypes/astype.py @@ -27,6 +27,7 @@ is_datetime64_dtype, is_datetime64tz_dtype, is_dtype_equal, + is_integer_dtype, is_object_dtype, is_timedelta64_dtype, pandas_dtype, @@ -133,7 +134,7 @@ def astype_nansafe( raise TypeError(f"cannot astype a timedelta from [{arr.dtype}] to [{dtype}]") - elif np.issubdtype(arr.dtype, np.floating) and np.issubdtype(dtype, np.integer): + elif np.issubdtype(arr.dtype, np.floating) and is_integer_dtype(dtype): return _astype_float_to_int_nansafe(arr, dtype, copy) elif is_object_dtype(arr.dtype): diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index 630f4cc3194f4..6bdf93c43c986 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -600,3 +600,9 @@ def test_astype_from_categorical_with_keywords(self): exp = Series(Categorical(lst, categories=list("abcdef"), ordered=True)) res = ser.astype(CategoricalDtype(list("abcdef"), ordered=True)) tm.assert_series_equal(res, exp) + + def test_astype_timedelta64_with_np_nan(self): + # GH45798 + result = Series([Timedelta(1), np.nan], dtype="timedelta64[ns]") + expected = Series([Timedelta(1), NaT], dtype="timedelta64[ns]") + tm.assert_series_equal(result, expected)