diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index db23bfdc8a5bd..00983485e782d 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -343,6 +343,7 @@ Other API changes See :ref:`units registration ` for more. - :meth:`Series.dropna` has dropped its ``**kwargs`` argument in favor of a single ``how`` parameter. Supplying anything else than ``how`` to ``**kwargs`` raised a ``TypeError`` previously (:issue:`29388`) +- :meth:`Series.interpolate` will issue a warning if using ``index`` or ``values`` method when index is not sorted. (:issue:`21037`) - When testing pandas, the new minimum required version of pytest is 5.0.1 (:issue:`29664`) - diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 744cde95cb668..b6128d40850fe 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -1,6 +1,7 @@ """ Routines for filling missing data. """ +import warnings import numpy as np @@ -21,6 +22,14 @@ from pandas.core.dtypes.missing import isna +class IndexNotSortedWarning(Warning): + """ + Warning raised when index is not sorted and interpolate with an unsupported method. + """ + + pass + + def mask_missing(arr, values_to_mask): """ Return a masking array of same size/shape as arr @@ -277,6 +286,9 @@ def interpolate_1d( inds = lib.maybe_convert_objects(inds) else: inds = xvalues + if not np.all(np.diff(inds) > 0): + msg = "interpolation method '%s' requires sorted index." % method + warnings.warn(msg, IndexNotSortedWarning) result[invalid] = np.interp(inds[invalid], inds[valid], yvalues[valid]) result[preserve_nans] = np.nan return result diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index 81bf1edbe86df..b5d173f70d06a 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -20,6 +20,7 @@ date_range, isna, ) +from pandas.core.missing import IndexNotSortedWarning import pandas.util.testing as tm @@ -1655,3 +1656,11 @@ def test_interpolate_timedelta_index(self, interp_methods_ind): pytest.skip( "This interpolation method is not supported for Timedelta Index yet." ) + + def test_interpolate_warn_index_not_sorted(self): + # GH 21037 + ts = pd.Series(data=[10, 9, np.nan, 2, 1], index=[10, 9, 3, 2, 1]) + with tm.assert_produces_warning(IndexNotSortedWarning): + ts.interpolate(method="index") + with tm.assert_produces_warning(IndexNotSortedWarning): + ts.interpolate(method="values")