Home > Back-end >  Numpy Upsample np.array / increase size of np.array by adding mean value of cosecuitive elements
Numpy Upsample np.array / increase size of np.array by adding mean value of cosecuitive elements

Time:11-18

I have an np.array which I need to make its size double/triple/quadruple. I want to do it by adding 1/2/3 elements between every 2 consecutive elements. for example:

np.array([1,2,3,4,5])

to be

np.array([1,1.5,2,2.5,3,3.5,4,4.5,5,5.5])

There is no problem doing that using python. but I need the fastest possible way, preferably using Numpy/Scipy.

CodePudding user response:

np.interp:

a = np.array([1,2,3,4,5])
ur = 2  # upsample rate
np.interp(np.arange((len(a)-1)*ur 1)/ur, xp=np.arange(len(a)), fp=a)
# output: array([1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5.])

CodePudding user response:

Maybe less efficient than Marat's one, but it works:

import numpy as np

my_list = [1,2,3,4,5]
new_list = np.concatenate([np.linspace(i, i 1, 3) for i in range(len(my_list))[1:]])
print(list(dict.fromkeys(new_list)))

Output:

[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

For numpy arrays it is equivalent.

  • Related