Issue
I am looking for some function that takes an input array of numbers and adds steps (range) between these numbers. I need to specify the length of the output’s array.
Example:
input_array = [1, 2, 5, 4]
output_array = do_something(input_array, output_length=10)
Result:
output_array => [1, 1.3, 1.6, 2, 3, 4, 5, 4.6, 4.3, 4]
len(output_array) => 10
Is there something like that, in Numpy for example?
I have a prototype of this function that uses dividing input array into pairs ([0,2]
, [2,5]
, [5,8]
) and filling "spaces" between with np.linspace()
but it don’t work well: https://onecompiler.com/python/3xwcy3y7d
def do_something(input_array, output_length):
import math
import numpy as np
output = []
in_between_steps = math.ceil(output_length/len(input_array))
prev_num = None
for num in input_array:
if prev_num is not None:
for in_num in np.linspace(start=prev_num, stop=num, num=in_between_steps, endpoint=False):
output.append(in_num)
prev_num = num
output.append(input_array[len(input_array)-1]) # manually add last item
return output
How it works:
input_array = [1, 2, 5, 4]
print(len(do_something(input_array, output_length=10))) # result: 10 OK
print(len(do_something(input_array, output_length=20))) # result: 16 NOT OK
print(len(do_something(input_array, output_length=200))) # result: 151 NOT OK
I have an array [1, 2, 5, 4]
and I need to "expand" a number of items in it but preserve the "shape":
Solution
There is numpy.interp
which might be what you are looking for.
import numpy as np
points = np.arange(4)
values = np.array([1,2,5,4])
x = np.linspace(0, 3, num=10)
np.interp(x, points, values)
output:
array([1. , 1.33333333, 1.66666667, 2. , 3. ,
4. , 5. , 4.66666667, 4.33333333, 4. ])
Answered By – Kevin
Answer Checked By – Willingham (BugsFixing Volunteer)