diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 2a7b37c95230c..bca92137891a0 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -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 @@ -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 diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx index d87a0641291b1..ddd38979e326c 100644 --- a/pandas/_libs/src/inference.pyx +++ b/pandas/_libs/src/inference.pyx @@ -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') diff --git a/pandas/tests/tools/test_numeric.py b/pandas/tests/tools/test_numeric.py index f82ad97d7b70f..664a97640387e 100644 --- a/pandas/tests/tools/test_numeric.py +++ b/pandas/tests/tools/test_numeric.py @@ -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)