Skip to content

Commit 429f294

Browse files
author
Khor Chean Wei
authored
Bug fix - Astype Timedelta64[ns] fails when np.nan is included (#45965)
1 parent b8c2e82 commit 429f294

File tree

3 files changed

+9
-2
lines changed

3 files changed

+9
-2
lines changed

doc/source/whatsnew/v1.5.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ Datetimelike
285285

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

290290
Time Zones
291291
^^^^^^^^^^

pandas/core/dtypes/astype.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
is_datetime64_dtype,
2828
is_datetime64tz_dtype,
2929
is_dtype_equal,
30+
is_integer_dtype,
3031
is_object_dtype,
3132
is_timedelta64_dtype,
3233
pandas_dtype,
@@ -133,7 +134,7 @@ def astype_nansafe(
133134

134135
raise TypeError(f"cannot astype a timedelta from [{arr.dtype}] to [{dtype}]")
135136

136-
elif np.issubdtype(arr.dtype, np.floating) and np.issubdtype(dtype, np.integer):
137+
elif np.issubdtype(arr.dtype, np.floating) and is_integer_dtype(dtype):
137138
return _astype_float_to_int_nansafe(arr, dtype, copy)
138139

139140
elif is_object_dtype(arr.dtype):

pandas/tests/series/methods/test_astype.py

+6
Original file line numberDiff line numberDiff line change
@@ -600,3 +600,9 @@ def test_astype_from_categorical_with_keywords(self):
600600
exp = Series(Categorical(lst, categories=list("abcdef"), ordered=True))
601601
res = ser.astype(CategoricalDtype(list("abcdef"), ordered=True))
602602
tm.assert_series_equal(res, exp)
603+
604+
def test_astype_timedelta64_with_np_nan(self):
605+
# GH45798
606+
result = Series([Timedelta(1), np.nan], dtype="timedelta64[ns]")
607+
expected = Series([Timedelta(1), NaT], dtype="timedelta64[ns]")
608+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)