Skip to content

Commit 386494d

Browse files
immaxchenTomAugspurger
authored andcommitted
BUG: fix Series.interpolate(method='index') with unsorted index (pandas-dev#29943)
* fix series interpolate bug with unsorted index GH21037
1 parent ed20822 commit 386494d

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

doc/source/whatsnew/v1.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -661,6 +661,7 @@ Numeric
661661
- Bug in :class:`UInt64Index` precision loss while constructing from a list with values in the ``np.uint64`` range (:issue:`29526`)
662662
- Bug in :class:`NumericIndex` construction that caused indexing to fail when integers in the ``np.uint64`` range were used (:issue:`28023`)
663663
- Bug in :class:`NumericIndex` construction that caused :class:`UInt64Index` to be casted to :class:`Float64Index` when integers in the ``np.uint64`` range were used to index a :class:`DataFrame` (:issue:`28279`)
664+
- Bug in :meth:`Series.interpolate` when using method=`index` with an unsorted index, would previously return incorrect results. (:issue:`21037`)
664665

665666
Conversion
666667
^^^^^^^^^^

pandas/core/missing.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,11 @@ def interpolate_1d(
277277
inds = lib.maybe_convert_objects(inds)
278278
else:
279279
inds = xvalues
280-
result[invalid] = np.interp(inds[invalid], inds[valid], yvalues[valid])
280+
# np.interp requires sorted X values, #21037
281+
indexer = np.argsort(inds[valid])
282+
result[invalid] = np.interp(
283+
inds[invalid], inds[valid][indexer], yvalues[valid][indexer]
284+
)
281285
result[preserve_nans] = np.nan
282286
return result
283287

pandas/tests/series/test_missing.py

+11
Original file line numberDiff line numberDiff line change
@@ -1649,3 +1649,14 @@ def test_interpolate_timedelta_index(self, interp_methods_ind):
16491649
pytest.skip(
16501650
"This interpolation method is not supported for Timedelta Index yet."
16511651
)
1652+
1653+
@pytest.mark.parametrize(
1654+
"ascending, expected_values",
1655+
[(True, [1, 2, 3, 9, 10]), (False, [10, 9, 3, 2, 1])],
1656+
)
1657+
def test_interpolate_unsorted_index(self, ascending, expected_values):
1658+
# GH 21037
1659+
ts = pd.Series(data=[10, 9, np.nan, 2, 1], index=[10, 9, 3, 2, 1])
1660+
result = ts.sort_index(ascending=ascending).interpolate(method="index")
1661+
expected = pd.Series(data=expected_values, index=expected_values, dtype=float)
1662+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)