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:
JavaScript
x
3
1
input_array = [1, 2, 5, 4]
2
output_array = do_something(input_array, output_length=10)
3
Result:
JavaScript
1
3
1
output_array => [1, 1.3, 1.6, 2, 3, 4, 5, 4.6, 4.3, 4]
2
len(output_array) => 10
3
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
JavaScript
1
21
21
1
def do_something(input_array, output_length):
2
3
import math
4
import numpy as np
5
6
output = []
7
8
in_between_steps = math.ceil(output_length/len(input_array))
9
10
prev_num = None
11
12
for num in input_array:
13
if prev_num is not None:
14
for in_num in np.linspace(start=prev_num, stop=num, num=in_between_steps, endpoint=False):
15
output.append(in_num)
16
prev_num = num
17
18
output.append(input_array[len(input_array)-1]) # manually add last item
19
20
return output
21
How it works:
JavaScript
1
5
1
input_array = [1, 2, 5, 4]
2
print(len(do_something(input_array, output_length=10))) # result: 10 OK
3
print(len(do_something(input_array, output_length=20))) # result: 16 NOT OK
4
print(len(do_something(input_array, output_length=200))) # result: 151 NOT OK
5
I have an array [1, 2, 5, 4]
and I need to “expand” a number of items in it but preserve the “shape”:
Advertisement
Answer
There is numpy.interp
which might be what you are looking for.
JavaScript
1
7
1
import numpy as np
2
3
points = np.arange(4)
4
values = np.array([1,2,5,4])
5
x = np.linspace(0, 3, num=10)
6
np.interp(x, points, values)
7
output:
JavaScript
1
3
1
array([1. , 1.33333333, 1.66666667, 2. , 3. ,
2
4. , 5. , 4.66666667, 4.33333333, 4. ])
3