Skip to content

Commit fc3ea3e

Browse files
dsaxtonJulianWgs
authored andcommitted
BUG: Don't raise TypeError when converting NA from string to numeric (pandas-dev#37268)
1 parent 1efc05b commit fc3ea3e

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

doc/source/whatsnew/v1.2.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,7 @@ Conversion
409409
Strings
410410
^^^^^^^
411411
- Bug in :meth:`Series.to_string`, :meth:`DataFrame.to_string`, and :meth:`DataFrame.to_latex` adding a leading space when ``index=False`` (:issue:`24980`)
412-
-
412+
- Bug in :func:`to_numeric` raising a ``TypeError`` when attempting to convert a string dtype :class:`Series` containing only numeric strings and ``NA`` (:issue:`37262`)
413413
-
414414

415415

pandas/_libs/lib.pyx

+1-1
Original file line numberDiff line numberDiff line change
@@ -2019,7 +2019,7 @@ def maybe_convert_numeric(ndarray[object] values, set na_values,
20192019
elif util.is_bool_object(val):
20202020
floats[i] = uints[i] = ints[i] = bools[i] = val
20212021
seen.bool_ = True
2022-
elif val is None:
2022+
elif val is None or val is C_NA:
20232023
seen.saw_null()
20242024
floats[i] = complexes[i] = NaN
20252025
elif hasattr(val, '__len__') and len(val) == 0:

pandas/tests/tools/test_to_numeric.py

+18
Original file line numberDiff line numberDiff line change
@@ -707,3 +707,21 @@ def test_precision_float_conversion(strrep):
707707
result = to_numeric(strrep)
708708

709709
assert result == float(strrep)
710+
711+
712+
@pytest.mark.parametrize(
713+
"values, expected",
714+
[
715+
(["1", "2", None], Series([1, 2, np.nan])),
716+
(["1", "2", "3"], Series([1, 2, 3])),
717+
(["1", "2", 3], Series([1, 2, 3])),
718+
(["1", "2", 3.5], Series([1, 2, 3.5])),
719+
(["1", None, 3.5], Series([1, np.nan, 3.5])),
720+
(["1", "2", "3.5"], Series([1, 2, 3.5])),
721+
],
722+
)
723+
def test_to_numeric_from_nullable_string(values, expected):
724+
# https://github.com/pandas-dev/pandas/issues/37262
725+
s = Series(values, dtype="string")
726+
result = to_numeric(s)
727+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)