1

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":

enter image description here

1
  • can you explain by what logic did you get that output array? (in your question not comments) Commented Mar 17, 2022 at 10:31

1 Answer 1

3

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.        ])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! With some arrays, the result is not as I expected - some values from the input array are missing or replaced (e.g. there is "4.8888" instead of "5"). But it is sufficient for my purposes.
@rotten77 Not sure, the length of x might be an odd number which can cause discrepancy. Maybe try setting the endpoint=False keyword for np.linspace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.