2
votes

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
What do you want to get if you extend the array [1, 5, 1, 7] to an array of length 6? - Aleksandr Kovalev
You can write a simple logic for what you want rather than finding an "easy way". - Pranav Totla
Then it should be, [1, 1+(5-1) * 3/5, 5+(1-5) * 1/5, 5+(1-5) * 4/5, 1+(7-1) * 2/5, 7] - Maytree23
@Maytree23 If you know what you want to get why don't you just write the code? - Aleksandr Kovalev
@Pranav Maytree23 might just be looking for a Pythonic way to it. - fixxxer

1 Answers

7
votes

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