diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index d2d5d40393b62..64dc9ea51eadd 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -500,7 +500,7 @@ Datetimelike Timedelta ^^^^^^^^^ -- +- Fixed bug where :meth:`DataFrame.astype` could not convert timedelta strings (:issue:`#22100`) - - diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index e369679d2146f..3f6f0bc4a8ff1 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -712,7 +712,8 @@ def astype_nansafe(arr, dtype, copy=True): elif is_object_dtype(arr): # work around NumPy brokenness, #1987 - if np.issubdtype(dtype.type, np.integer): + is_time = is_timedelta64_dtype(dtype) + if np.issubdtype(dtype.type, np.integer) and is_time: return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape) # if we have a datetime/timedelta array of objects diff --git a/pandas/tests/dtypes/test_cast.py b/pandas/tests/dtypes/test_cast.py index 0d6382424ccf5..8c8e6c9a4c242 100644 --- a/pandas/tests/dtypes/test_cast.py +++ b/pandas/tests/dtypes/test_cast.py @@ -24,7 +24,8 @@ find_common_type, construct_1d_object_array_from_listlike, construct_1d_ndarray_preserving_na, - construct_1d_arraylike_from_scalar) + construct_1d_arraylike_from_scalar, + astype_nansafe) from pandas.core.dtypes.dtypes import ( CategoricalDtype, DatetimeTZDtype, @@ -456,3 +457,13 @@ def test_cast_1d_arraylike_from_scalar_categorical(self): def test_construct_1d_ndarray_preserving_na(values, dtype, expected): result = construct_1d_ndarray_preserving_na(values, dtype=dtype) tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize('arr, dtype, expected', [ + (np.array(['0:0:1'], dtype='O'), 'm8[ns]', 'm8[ns]'), + (np.array(['0:0:1'], dtype='O'), 'm8', 'float64'), +]) +def test_astype_nansafe(arr, dtype, expected): + # GH #22100 + result = astype_nansafe(arr, dtype) + assert is_dtype_equal(result.dtype, expected)