插值然后外推边界值

Interpolate then extrapolate boundary values

以下程序不在 0,7 处插入值

import pandas as pd
import numpy as np

s = pd.Series([np.nan, 2, 4,np.nan, 8, np.nan], [0,1,2,4,5,7])
interp = s.interpolate(method='akima', order=2)
print(s)
print(interp)

0    NaN
1    2.0
2    4.0
4    NaN
5    8.0
7    NaN
dtype: float64
0         NaN
1    2.000000
2    4.000000
4    6.888889
5    8.000000
7         NaN
dtype: float64

如何获取 0 和 7 的值?外推?

好吧,这要视情况而定,因为每种插值方法的工作方式都不同。
如果您可以使用 spline / pchip / linear 方法,那么您可以使用:

my_method='pchip' #or 'linear' or 'spline'
interp = s.interpolate(method=my_method, order=2, limit=2, limit_direction='both')

我知道这些方法适用于您的情况,但也许还有更多方法。

参数limit指定为:

Maximum number of consecutive NaNs to fill. Must be greater than 0.

limit_direction指定为:

If limit is specified, consecutive NaNs will be filled in this direction.

更多信息在pandas.Series.interpolate docs