Skip to content

Bug fix - Astype Timedelta64[ns] fails when np.nan is included #45965

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Feb 27, 2022
Merged
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ Datetimelike

Timedelta
^^^^^^^^^
-
- Bug in :func:`astype_nansafe` astype("timedelta64[ns]") fails when np.nan is included (:issue:`45798`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a user-facing method we can refer to?


Time Zones
^^^^^^^^^^
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/dtypes/astype.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
is_datetime64_dtype,
is_datetime64tz_dtype,
is_dtype_equal,
is_integer_dtype,
is_object_dtype,
is_timedelta64_dtype,
pandas_dtype,
Expand Down Expand Up @@ -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):
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/series/methods/test_astype.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)