How to extend an array with linear interpolation

时间秒杀一切 提交于 2019-12-13 20:04:03

问题


What I want is to extend an array of length m to an array of length n (n>m), and interpolate the missing values linearly.

For example, I want to extend this array [1,5,1,7] to an array of length 7, the result should be [1,3,5,3,1,5,7], where the bold figures result from linear interpolation.

Is there an easy way to do this in Python? Thanks in advance.


回答1:


The interp function from numpy can do what you want.

Example:

>>> xp = [1, 2, 3]
>>> fp = [3, 2, 0]
>>> np.interp(2.5, xp, fp)
1.0
>>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp)
array([ 3. ,  3. ,  2.5 ,  0.56,  0. ])



回答2:


use extend :

a = [1, 2, 3] a.extend([4, 5]) print (a)

output:

[1, 2, 3, 4, 5]

you will have to use your own logic for the input array for extend




回答3:


To interleave two lists, you could use:

In [240]: x = [1, 5, 1, 7]

In [241]: y = [3, 3, 5]

In [242]: from itertools import chain, izip

In [243]: list(chain.from_iterable(izip(x, y)))
Out[243]: [1, 3, 5, 3, 1, 5]

as you see above it would stop at the shorter list. Check this answer for overcoming this limitation.



来源:https://stackoverflow.com/questions/30023326/how-to-extend-an-array-with-linear-interpolation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!