python插值方法
1. numpy.interp
函数原型:
numpy.interp(x, xp, fp, left=None, right=None, period=None)
用法:
- 某一点的插值结果
xp = [1, 2, 3]
fp = [3, 2, 0]
np.interp(2.5, xp, fp)
输出:1.0
- 向量化运算
np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp)
输出:array([3. , 3. , 2.5 , 0.56, 0. ])
- 左右越界填充值
UNDEF = -99.0
np.interp(3.14, xp, fp, right=UNDEF)
输出:-99.0
2. scipy.interpolate.interp1d
函数原型:
class scipy.interpolate.interp1d(x, y, kind='linear', axis=- 1, copy=True, bounds_error=None, fill_value=nan, assume_sorted=False)
返回一个函数
用法:
- 常规用法
import matplotlib.pyplot as plt
from scipy import interpolate
x = np.arange(0, 10)
y = np.exp(-x/3.0)
f = interpolate.interp1d(x, y)
xnew = np.arange(0, 9, 0.1)
ynew = f(xnew) # use interpolation function returned by `interp1d`
plt.plot(x, y, 'o', xnew, ynew, '-')
plt.show()
- 通过设置参数fiil_value=‘extrapolate’,可以对越界的点额外进行插值。
fill_value:array-like or (array-like, array_like) or “extrapolate” optional
If “extrapolate”, then points outside the data range will be extrapolated.