diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 4db0f75586ead..fe88622a04bb4 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -1300,10 +1300,12 @@ def _ensure_numeric(x): elif not (is_float(x) or is_integer(x) or is_complex(x)): try: x = float(x) - except Exception: + except ValueError: + # e.g. "1+1j" or "foo" try: x = complex(x) - except Exception: + except ValueError: + # e.g. "foo" raise TypeError( "Could not convert {value!s} to numeric".format(value=x) ) diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py index 21ab28c94c978..eb39f01657b90 100644 --- a/pandas/tests/test_nanops.py +++ b/pandas/tests/test_nanops.py @@ -911,10 +911,11 @@ def test_non_convertable_values(self): msg = "Could not convert foo to numeric" with pytest.raises(TypeError, match=msg): nanops._ensure_numeric("foo") - msg = "Could not convert {} to numeric" + + # with the wrong type, python raises TypeError for us + msg = "argument must be a string or a number" with pytest.raises(TypeError, match=msg): nanops._ensure_numeric({}) - msg = r"Could not convert \[\] to numeric" with pytest.raises(TypeError, match=msg): nanops._ensure_numeric([])