Skip to content

Commit

Permalink
Bug fix - Astype Timedelta64[ns] fails when np.nan is included (panda…
Browse files Browse the repository at this point in the history
  • Loading branch information
Khor Chean Wei authored Feb 27, 2022
1 parent b8c2e82 commit 429f294
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 2 deletions.
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 @@ -285,7 +285,7 @@ Datetimelike

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

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)

0 comments on commit 429f294

Please sign in to comment.