当x-array的前2个值相同时,为什么scipy中的interp1d会给出NaN?(fill_value = 0)

Ski*_*ony 5 python interpolation numpy scipy

import numpy as np
from scipy.interpolate import interp1d

x = np.array([ 0,  0,   0,  0,   0,  30])
time = np.array([ 5,  5,  10,  10,  10,  20])

intx = interp1d(time,x,'linear', 0, True, False, 0)
print intx([4,5,5,6,10,11,20, 20.0001])

>>> [  0.  nan  nan   0.   0.   3.  30.   0.]
Run Code Online (Sandbox Code Playgroud)

如您所见,除了时间值==第一对值之外的所有情况下,插值返回实数.

我知道numpy.unique(),这只是一个学术问题.这是在iPython中运行的Anaconda Python 2.7.

谢谢!

jab*_*edo 8

你的问题是你试图插入超出间隔的点,这会导致它在尝试计算两点之间的斜率时scipy.interpolate.interp1d启动RuntimeWarning(它发生在第416行的interpolate.py中):

slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None]
Run Code Online (Sandbox Code Playgroud)

看看在间隔内移动积分时会发生什么:

>>> import numpy as np
>>> from scipy.interpolate import interp1d
>>> x = np.array([ 5,  5,  10,  10,  10,  20])
>>> y = np.array([ 0,  0,   0,  0,   0,  30])
>>> X = np.array([5.1,5.1,5.1,6,10,11,20, 19.999])
>>> f = interp1d(x,y,'linear', 0, True, False, 0)
>>> Y = f(X)
 [  0.      0.      0.      0.      0.      3.     30.     29.997]
Run Code Online (Sandbox Code Playgroud)

如果您绘制它,您可以看到一切都有意义:

在此输入图像描述

这是如何interp1d工作:

  1. 您传递xyinterp1d和它创建了一个f可调用的方法
  2. 然后传递x_new要评估的新值,f并执行以下步骤: