6
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.]

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

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

谢谢!

4

2 回答 2

8

您的问题是您正在尝试对区间外的点进行插值,这会导致在尝试计算两点之间的斜率时scipy.interpolate.interp1d启动 a (它发生在 interpolate.py 中的第 416 行附近):RuntimeWarning

slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None]

查看在区间内移动点时会发生什么:

>>> 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]

如果你绘制它,你会发现一切都是有道理的:

在此处输入图像描述

这是如何interp1d工作的:

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

    • 在原始数据中查找要插入的值的位置。

      >>> x_new_indices = np.searchsorted(x, X)
      
    • 剪辑 x_new_indices 使它们在x索引范围内且至少为 1。消除错误插值x_new[n] = x[0]

      >>> x_new_indices = x_new_indices.clip(1, len(x)-1).astype(int)
      
    • 计算每个x_new值所在区域的斜率。

      >>> lo = x_new_indices - 1
      >>> hi = x_new_indices
      >>> x_lo = x[lo]
      >>> x_hi = x[hi]
      >>> y_lo = y[lo]
      >>> y_hi = y[hi]
      
    • 计算 中每个条目的实际值x_new

      >>> slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None]
      >>> y_new = slope*(x_new - x_lo)[:, None] + y_lo
      
于 2013-09-25T08:30:07.103 回答
1

In the above case, I'd suggest just sample points for the Y variable. Eg. consider the following points.

x= [275, 275]
y= [120, 120]

the above points represent a line parallel to the Y-axis. Therefore, the slope of the line is undefined. So, here you can sample points just for the Y variable and replicate value of the X variable for each of them. You will find the below plots intuitive.
Plot 1 -
Two initial points

Plot 2 -
Sample only y points keeping x same!

于 2019-10-18T16:44:21.480 回答