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
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
7 changes: 7 additions & 0 deletions pandas/tests/series/indexing/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,3 +482,10 @@ def test_getitem_str_second_with_datetimeindex():
msg = r"Timestamp\('2012-01-02 18:01:02-0600', tz='US/Central', freq='S'\)"
with pytest.raises(KeyError, match=msg):
df[df.index[2]]


Copy link
Contributor

Choose a reason for hiding this comment

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

these are astype tests, pls move them.

def test_astype_timedelta64_with_np_nan():
# GH45798
result = Series([1, np.nan]).astype("timedelta64[ns]")
expected = Series([1, pd.NaT]).astype("timedelta64[ns]")
Copy link
Contributor

Choose a reason for hiding this comment

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

to be explictily construct here the expected

Copy link
Contributor Author

@weikhor weikhor Feb 16, 2022

Choose a reason for hiding this comment

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

Hi I do not understand. Can please give more details? Thank.

Copy link
Member

Choose a reason for hiding this comment

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

if the method being tested is Series.astype, then the test belongs in tests.series.methods.test_astype

tm.assert_series_equal(result, expected)