How to stretch an array to a new length while keeping same value distribution?

Viewed 477

If I have a numpy array of length n that looks like this [2.456970453262329, 2.3738574981689453,... 1.28790283203125,]

and I want to "stretch" is so that it now has length m (m>n) but still keeps the same general distribution of values, how could I do that? Is there a numpy module for such a transformation?

e.g. for n=3 and m=5 [1, 2, 3] --> [1, 1.5, 2, 2.5, 3]

2 Answers

I think you are just looking for linear interpolation. np.interp will do the trick:

import numpy as np


# wrapper function for convenience
def interp1d(array: np.ndarray, new_len: int) -> np.ndarray:
    la = len(array)
    return np.interp(np.linspace(0, la - 1, num=new_len), np.arange(la), array)


print(interp1d(np.asarray([1, 2, 3]), new_len=5)) # [1.  1.5 2.  2.5 3. ]
print(interp1d(np.asarray([0, 2, 3]), new_len=6)) # [0.  0.8 1.6 2.2 2.6 3. ]
# can even shorten arrays as well
print(interp1d(np.asarray([0, -2, 1, 3]), new_len=3)) # [ 0.  -0.5  3. ]
Related