Skip to content

BUG: Don't segfault to_numeric when input is empty #16305

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions doc/source/whatsnew/v0.20.2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Bug Fixes
Conversion
^^^^^^^^^^


- Bug in ``pd.to_numeric()`` in which empty data inputs were causing Python to crash (:issue:`16302`)


Indexing
Expand All @@ -49,7 +49,7 @@ Indexing
I/O
^^^

- Bug that would force importing of the clipboard routines unecessarily, potentially causing an import error on startup (:issue:`16288`)
- Bug that would force importing of the clipboard routines unnecessarily, potentially causing an import error on startup (:issue:`16288`)


Plotting
Expand Down
5 changes: 5 additions & 0 deletions pandas/_libs/src/inference.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -947,8 +947,13 @@ def maybe_convert_numeric(ndarray[object] values, set na_values,
-------
numeric_array : array of converted object values to numerical ones
"""

if len(values) == 0:
return np.array([], dtype='i8')

# fastpath for ints - try to convert all based on first value
cdef object val = values[0]

if util.is_integer_object(val):
try:
maybe_ints = values.astype('i8')
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/tools/test_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,21 @@

class TestToNumeric(object):

def test_empty(self):
# see gh-16302
s = pd.Series([], dtype=object)

res = to_numeric(s)
expected = pd.Series([], dtype=np.int64)

tm.assert_series_equal(res, expected)

# Original issue example
res = to_numeric(s, errors='coerce', downcast='integer')
expected = pd.Series([], dtype=np.int8)

tm.assert_series_equal(res, expected)

def test_series(self):
s = pd.Series(['1', '-3.14', '7'])
res = to_numeric(s)
Expand Down