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.
谢谢!
你的问题是你试图插入超出间隔的点,这会导致它在尝试计算两点之间的斜率时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
工作:
x
和y
到interp1d
和它创建了一个f
可调用的方法然后传递x_new
要评估的新值,f
并执行以下步骤:
找到原始数据中的哪个位置,将插入要插值的值.
>>> x_new_indices = np.searchsorted(x, X)
Run Code Online (Sandbox Code Playgroud)剪辑x_new_indices,使它们在x
索引范围内并且至少为1.删除错误插值x_new[n] = x[0]
>>> x_new_indices = x_new_indices.clip(1, len(x)-1).astype(int)
Run Code Online (Sandbox Code Playgroud)计算每个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]
Run Code Online (Sandbox Code Playgroud)计算每个条目的实际值x_new
.
>>> slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None]
>>> y_new = slope*(x_new - x_lo)[:, None] + y_lo
Run Code Online (Sandbox Code Playgroud) 归档时间: |
|
查看次数: |
2685 次 |
最近记录: |