SciPy文档解释了interp1d
函数的kind
参数可以使用'linear'
, 'nearest'
, 'zero'
, 'slinear'
, 'quadratic'
, 'cubic'
这六个值。最后三个是样条插值阶数,而'linear'
则不需要解释。那么'nearest'
和'zero'
分别表示什么意思呢?
SciPy文档解释了interp1d
函数的kind
参数可以使用'linear'
, 'nearest'
, 'zero'
, 'slinear'
, 'quadratic'
, 'cubic'
这六个值。最后三个是样条插值阶数,而'linear'
则不需要解释。那么'nearest'
和'zero'
分别表示什么意思呢?
nearest
选项“捕捉”到最近的数据点。zero
是一阶样条插值。它在任意点的值为最后一个原始值。linear
执行线性插值,slinear
使用一阶样条插值。它们使用不同的代码,但可能会产生类似但微妙不同的结果。quadratic
使用二阶样条插值。cubic
使用三阶样条插值。请注意,k
参数还可以接受指定样条插值次数的整数。
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as interpolate
np.random.seed(6)
kinds = ('nearest', 'zero', 'linear', 'slinear', 'quadratic', 'cubic')
N = 10
x = np.linspace(0, 1, N)
y = np.random.randint(10, size=(N,))
new_x = np.linspace(0, 1, 28)
fig, axs = plt.subplots(nrows=len(kinds)+1, sharex=True)
axs[0].plot(x, y, 'bo-')
axs[0].set_title('raw')
for ax, kind in zip(axs[1:], kinds):
new_y = interpolate.interp1d(x, y, kind=kind)(new_x)
ax.plot(new_x, new_y, 'ro-')
ax.set_title(kind)
plt.show()
‘nearest’ 返回距离参数最近的X个数据点,或者使用距离x最近的数据点对函数y=f(x)进行插值
'zero' 我猜相当于截断参数并使用最靠近零的数据点