Skip to content

Commit 4e36a9b

Browse files
REGR: to_timedelta precision issues with floating data
1 parent e28ae70 commit 4e36a9b

File tree

3 files changed

+11
-7
lines changed

3 files changed

+11
-7
lines changed

doc/source/whatsnew/v0.24.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ Fixed Regressions
3131
- Fixed regression in ``IntervalDtype`` construction where passing an incorrect string with 'Interval' as a prefix could result in a ``RecursionError``. (:issue:`25338`)
3232
- Fixed regression in creating a period-dtype array from a read-only NumPy array of period objects. (:issue:`25403`)
3333
- Fixed regression in :class:`Categorical`, where constructing it from a categorical ``Series`` and an explicit ``categories=`` that differed from that in the ``Series`` created an invalid object which could trigger segfaults. (:issue:`25318`)
34+
- Fixed regression in :func:`to_timedelta` loosing precision when converting floating data to ``Timedelta`` data (:issue:`25077`).
3435
- Fixed pip installing from source into an environment without NumPy (:issue:`25193`)
3536

3637
.. _whatsnew_0242.enhancements:

pandas/core/arrays/timedeltas.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -918,13 +918,9 @@ def sequence_to_td64ns(data, copy=False, unit="ns", errors="raise"):
918918
copy = copy and not copy_made
919919

920920
elif is_float_dtype(data.dtype):
921-
# treat as multiples of the given unit. If after converting to nanos,
922-
# there are fractional components left, these are truncated
923-
# (i.e. NOT rounded)
924-
mask = np.isnan(data)
925-
coeff = np.timedelta64(1, unit) / np.timedelta64(1, 'ns')
926-
data = (coeff * data).astype(np.int64).view('timedelta64[ns]')
927-
data[mask] = iNaT
921+
# object_to_td64ns has custom logic for float -> int conversion
922+
# to avoid precision issues
923+
data = objects_to_td64ns(data, unit=unit, errors=errors)
928924
copy = False
929925

930926
elif is_timedelta64_dtype(data.dtype):

pandas/tests/indexes/timedeltas/test_tools.py

+7
Original file line numberDiff line numberDiff line change
@@ -181,3 +181,10 @@ def test_to_timedelta_on_missing_values(self):
181181

182182
actual = pd.to_timedelta(pd.NaT)
183183
assert actual.value == timedelta_NaT.astype('int64')
184+
185+
def test_to_timedelta_float(self):
186+
# https://github.com/pandas-dev/pandas/issues/25077
187+
arr = np.arange(0, 1, 1e-6)[-10:]
188+
result = pd.to_timedelta(arr, unit='s')
189+
expected_asi8 = np.arange(999990000, int(1e9), 1000, dtype='int64')
190+
tm.assert_numpy_array_equal(result.asi8, expected_asi8)

0 commit comments

Comments
 (0)