diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 3a8c81b5e9281..100d2a406c577 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -243,6 +243,10 @@ Documentation Changes Bug Fixes ~~~~~~~~~ +**Data-type specific** + +- Bug in :meth:`Series.interpolate()` where appropiate error was not raised when interpolating with a non-numeric index column (:issue:`21662`) + Categorical ^^^^^^^^^^^ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 26c23b84a9c04..80fffd259c6ab 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6024,6 +6024,13 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False, raise NotImplementedError("Interpolation with NaNs in the index " "has not been implemented. Try filling " "those NaNs before interpolating.") + + if not is_numeric_dtype(index): + raise ValueError("Index column must be numeric when using any " + "interpolation method other than linear. Try " + "setting a numeric index column before " + "interpolating.") + data = _maybe_transposed_self._data new_data = data.interpolate(method=method, axis=ax, index=index, values=_maybe_transposed_self, limit=limit, diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index 533bff0384ad9..a41b680f8648a 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -1008,3 +1008,20 @@ def test_pipe_panel(self): with pytest.raises(ValueError): result = wp.pipe((f, 'y'), x=1, y=1) + + def test_interpolate(self): + # GH 21662 + # Using a numeric index column + df = DataFrame([0, 1, np.nan, 3], index=[1, 2, 3, 4]) + series = Series(df[0]) + assert series.interpolate( + method="quadratic").equals(series.interpolate(method="linear")) + + # Using a non-numeric index column + df = DataFrame([0, 1, np.nan, 3], index=["A", "B", "C", "D"]) + series = Series(df[0]) + with pytest.raises(ValueError, match="Index column must be numeric " + "when using any interpolation method other than linear. Try " + "setting a numeric index column before interpolating."): + + result = series.interpolate(method="quadratic")