Skip to content

Commit 3af8044

Browse files
Backport PR #35582: BUG: to_timedelta fails on Int64 Series with null values (#35602)
Co-authored-by: Eric Goddard <[email protected]>
1 parent 33ec020 commit 3af8044

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

doc/source/whatsnew/v1.1.1.rst

+5
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,11 @@ Categorical
3737
-
3838
-
3939

40+
**Timedelta**
41+
42+
- Bug in :meth:`to_timedelta` fails when arg is a :class:`Series` with `Int64` dtype containing null values (:issue:`35574`)
43+
44+
4045
**Numeric**
4146

4247
-

pandas/core/arrays/timedeltas.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929

3030
from pandas.core import nanops
3131
from pandas.core.algorithms import checked_add_with_arr
32-
from pandas.core.arrays import datetimelike as dtl
32+
from pandas.core.arrays import IntegerArray, datetimelike as dtl
3333
from pandas.core.arrays._ranges import generate_regular_range
3434
import pandas.core.common as com
3535
from pandas.core.construction import extract_array
@@ -921,6 +921,8 @@ def sequence_to_td64ns(data, copy=False, unit=None, errors="raise"):
921921
elif isinstance(data, (ABCTimedeltaIndex, TimedeltaArray)):
922922
inferred_freq = data.freq
923923
data = data._data
924+
elif isinstance(data, IntegerArray):
925+
data = data.to_numpy("int64", na_value=tslibs.iNaT)
924926

925927
# Convert whatever we have into timedelta64[ns] dtype
926928
if is_object_dtype(data.dtype) or is_string_dtype(data.dtype):

pandas/tests/tools/test_to_timedelta.py

+13
Original file line numberDiff line numberDiff line change
@@ -166,3 +166,16 @@ def test_to_timedelta_ignore_strings_unit(self):
166166
arr = np.array([1, 2, "error"], dtype=object)
167167
result = pd.to_timedelta(arr, unit="ns", errors="ignore")
168168
tm.assert_numpy_array_equal(result, arr)
169+
170+
def test_to_timedelta_nullable_int64_dtype(self):
171+
# GH 35574
172+
expected = Series([timedelta(days=1), timedelta(days=2)])
173+
result = to_timedelta(Series([1, 2], dtype="Int64"), unit="days")
174+
175+
tm.assert_series_equal(result, expected)
176+
177+
# IntegerArray Series with nulls
178+
expected = Series([timedelta(days=1), None])
179+
result = to_timedelta(Series([1, None], dtype="Int64"), unit="days")
180+
181+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)