Skip to content

Commit e740857

Browse files
authored
BUG: fix to_numeric raises TypeError for Timedelta and Timestamp scalar (#59974)
* BUG: fix to_numeric raises TypeError for Timedelta and Timestamp scalar * Add whatsnew
1 parent b63c795 commit e740857

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -701,6 +701,7 @@ Other
701701
- Bug in :func:`eval` on :class:`ExtensionArray` on including division ``/`` failed with a ``TypeError``. (:issue:`58748`)
702702
- Bug in :func:`eval` where the names of the :class:`Series` were not preserved when using ``engine="numexpr"``. (:issue:`10239`)
703703
- Bug in :func:`eval` with ``engine="numexpr"`` returning unexpected result for float division. (:issue:`59736`)
704+
- Bug in :func:`to_numeric` raising ``TypeError`` when ``arg`` is a :class:`Timedelta` or :class:`Timestamp` scalar. (:issue:`59944`)
704705
- Bug in :func:`unique` on :class:`Index` not always returning :class:`Index` (:issue:`57043`)
705706
- Bug in :meth:`DataFrame.apply` where passing ``engine="numba"`` ignored ``args`` passed to the applied function (:issue:`58712`)
706707
- Bug in :meth:`DataFrame.eval` and :meth:`DataFrame.query` which caused an exception when using NumPy attributes via ``@`` notation, e.g., ``df.eval("@np.floor(a)")``. (:issue:`58041`)

pandas/core/tools/numeric.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@
1111
lib,
1212
missing as libmissing,
1313
)
14+
from pandas._libs.tslibs import (
15+
Timedelta,
16+
Timestamp,
17+
)
1418
from pandas.util._validators import check_dtype_backend
1519

1620
from pandas.core.dtypes.cast import maybe_downcast_numeric
@@ -189,6 +193,8 @@ def to_numeric(
189193
return float(arg)
190194
if is_number(arg):
191195
return arg
196+
if isinstance(arg, (Timedelta, Timestamp)):
197+
return arg._value
192198
is_scalars = True
193199
values = np.array([arg], dtype="O")
194200
elif getattr(arg, "ndim", 1) > 1:

pandas/tests/tools/test_to_numeric.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,21 @@ def test_timedelta(transform_assert_equal):
384384
assert_equal(result, expected)
385385

386386

387+
@pytest.mark.parametrize(
388+
"scalar",
389+
[
390+
pd.Timedelta(1, "D"),
391+
pd.Timestamp("2017-01-01T12"),
392+
pd.Timestamp("2017-01-01T12", tz="US/Pacific"),
393+
],
394+
)
395+
def test_timedelta_timestamp_scalar(scalar):
396+
# GH#59944
397+
result = to_numeric(scalar)
398+
expected = to_numeric(Series(scalar))[0]
399+
assert result == expected
400+
401+
387402
def test_period(request, transform_assert_equal):
388403
transform, assert_equal = transform_assert_equal
389404

0 commit comments

Comments
 (0)