NumPy:如何在不同的时间步长之间插值两个数组?

14
我正在寻找一种在时间起点和终点之间进行简单的线性插值的方法,这两个数组具有相同的长度:


fst = np.random.random_integers(5, size=(10.))
>>> array([4, 4, 1, 3, 1, 4, 3, 2, 5, 2])
snd = np.random.random_integers(5, size=(10.))
>>> array([1, 1, 3, 4, 1, 5, 5, 5, 4, 3])

在我的起点和终点之间,有3个时间步骤。如何在 fstsnd 之间进行插值?举例来说,我想要能够获取 fstsnd 的第一个条目,并检索每个时间步骤的值,如下所示:

np.interp(1, [1,5], [4,1])    
np.interp(2, [1,5], [4,1])
...
# that is
np.interp([1,2,3,4,5], [1,5], [4,1])
>>> array([ 4.  ,  3.25,  2.5 ,  1.75,  1.  ])

但不仅限于第一个条目,而是整个数组。

显然,这样做行不通:

np.interp(1, [1,5], [fst,snd])

好的,我知道我会进入一个循环,例如:

[np.interp(2, [1,5], [item,snd[idx]]) for idx,item in enumerate(fst)]
>>> [3.25, 3.25, 1.5, 3.25, 1.0, 4.25, 3.5, 2.75, 4.75, 2.25]

但我相信当您循环遍历NumPy数组时,您正在做一些根本错误的事情。

2个回答

13

如果您将样本组成2D矩阵,那么在scipy.interpolate.interp1d中的设施可以轻松实现此操作。在您的情况下,您可以构建一个2xN数组,并构建一个沿列操作的插值函数:

from scipy.interpolate import interp1d
fst = np.array([4, 4, 1, 3, 1, 4, 3, 2, 5, 2])
snd = np.array([1, 1, 3, 4, 1, 5, 5, 5, 4, 3])
linfit = interp1d([1,5], np.vstack([fst, snd]), axis=0)

您可以在任何感兴趣的时间生成插值向量。例如,linfit(2) 会产生:

array([ 3.25,  3.25,  1.5 ,  3.25,  1.  ,  4.25,  3.5 ,  2.75,  4.75,  2.25])

或者您可以使用时间值向量调用linfit(),例如:linfit([1,2,3])将得到:

array([[ 4.  ,  4.  ,  1.  ,  3.  ,  1.  ,  4.  ,  3.  ,  2.  ,  5.  ,  2.  ],
       [ 3.25,  3.25,  1.5 ,  3.25,  1.  ,  4.25,  3.5 ,  2.75,  4.75,           2.25],
       [ 2.5 ,  2.5 ,  2.  ,  3.5 ,  1.  ,  4.5 ,  4.  ,  3.5 ,  4.5 , 2.5 ]])

如果您只是进行线性插值,您也可以尝试这样做:
((5-t)/(5-1)) * fst + ((t-1)/(5-1)) * snd

直接计算任意时间t的插值向量。


1

这种方法类似,但使用更简单的符号表示:

#Suppose you have some start and end points
start_vector = numpy.array([4, 4, 1, 3, 1, 4, 3, 2, 5, 2])
end_vector = numpy.array([-40, 40, -10, -30, 10, 40, 30, -8, 50, 20])

#To get a vector that's located in-between:
intermediate_vector = start_vector + (end_vector - start_vector) * fraction

fraction是一个介于0和1之间的数字,它决定了你在起点和终点之间的位置(0将你放在start_vector,1将给你end_vector,而0.5将以线性方式给你这两个向量之间的中间点,依此类推)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接