简体   繁体   English

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

[英]numpy: how interpolate between two arrays for various timesteps?

I'm looking for a way to do a simple linear interpolation between two numpy arrays that represent a start and endpoint in time. 我正在寻找一种方法,可以在表示时间起点和终点的两个numpy数组之间进行简单的线性插值。

The two arrays have the same length: 这两个数组的长度相同:

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

Between my start and endpoint there are 3 timesteps. 在我的起点和终点之间,有3个时间步。 How can I interpolate between fst and snd ? 如何在fstsnd之间进行插值? I want to be able, taking the first entry of fst and snd as an example, to retrieve the value of each timestep like 我希望能够以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.  ])

But than not just for the first entry but over the whole array. 但是,不仅是第一个条目,而且还包括整个数组。

Obviously, this won't do it: 显然,这不会做到:

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

Well I know I get there in a loop, eg 好吧,我知道我会循环到达那里,例如

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

but I believe when you are lopping over numpy arrays you are doing something fundamentally wrong. 但是我相信当您使用numpy数组时,您所做的事情根本上是错误的。

The facilities in scipy.interpolate.interp1d allow this to be done quite easily if you form your samples into a 2D matrix. 如果您将样本形成2D矩阵,则scipy.interpolate.interp1d中的设施使此操作非常容易。 In your case, you can construct a 2xN array, and construct an interpolation function that operates down the columns: 在您的情况下,您可以构造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)

You can then generate an interpolated vector at any time of interest. 然后,您可以在感兴趣的任何时间生成插值矢量。 For example linfit(2) produces: 例如linfit(2)产生:

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

or you can invoke linfit() with a vector of time values, eg linfit([1,2,3]) gives: 或者您可以使用时间值向量调用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 ]])

If you're only doing linear interpolation, you could also just do something like: 如果仅执行线性插值,则还可以执行以下操作:

((5-t)/(5-1)) * fst + ((t-1)/(5-1)) * snd

to directly compute the interpolated vector at any time t. 在任何时间t直接计算插值向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM