Skip to content

Commit 84b024f

Browse files
gfyoungTomAugspurger
authored andcommitted
BUG: Don't segfault to_numeric when input is empty (#16305)
Closes gh-16302. (cherry picked from commit 81aa70c)
1 parent ce15e66 commit 84b024f

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

doc/source/whatsnew/v0.20.2.txt

+2-2
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ Bug Fixes
3939
Conversion
4040
^^^^^^^^^^
4141

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

4444

4545
Indexing
@@ -51,7 +51,7 @@ Indexing
5151
I/O
5252
^^^
5353

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

5656

5757
Plotting

pandas/_libs/src/inference.pyx

+5
Original file line numberDiff line numberDiff line change
@@ -947,8 +947,13 @@ def maybe_convert_numeric(ndarray[object] values, set na_values,
947947
-------
948948
numeric_array : array of converted object values to numerical ones
949949
"""
950+
951+
if len(values) == 0:
952+
return np.array([], dtype='i8')
953+
950954
# fastpath for ints - try to convert all based on first value
951955
cdef object val = values[0]
956+
952957
if util.is_integer_object(val):
953958
try:
954959
maybe_ints = values.astype('i8')

pandas/tests/tools/test_numeric.py

+15
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,21 @@
1111

1212
class TestToNumeric(object):
1313

14+
def test_empty(self):
15+
# see gh-16302
16+
s = pd.Series([], dtype=object)
17+
18+
res = to_numeric(s)
19+
expected = pd.Series([], dtype=np.int64)
20+
21+
tm.assert_series_equal(res, expected)
22+
23+
# Original issue example
24+
res = to_numeric(s, errors='coerce', downcast='integer')
25+
expected = pd.Series([], dtype=np.int8)
26+
27+
tm.assert_series_equal(res, expected)
28+
1429
def test_series(self):
1530
s = pd.Series(['1', '-3.14', '7'])
1631
res = to_numeric(s)

0 commit comments

Comments
 (0)