I have the following numpy array:
a = np.array([1,4,2])
I wish to create a new array by dividing this equally by 5 between each element in the a
array to get:
b = [1., 1.75, 2.5, 3.25, 4., 3.5, 3., 2.5, 2.]
How can I do this efficiently in python?
You are looking for a linear interpolation for a 1-d array, which can be done using NumPy.interp
.
s = 4 # number of intervals between two numbers
l = (a.size - 1) * s + 1 # total length after interpolation
np.interp(np.arange(l), np.arange(l, step=s), a) # interpolate
# array([1. , 1.75, 2.5 , 3.25, 4. , 3.5 , 3. , 2.5 , 2. ])
Other option using arange
:
import numpy as np
a = np.array([1,4,2])
res = np.array([float(a[-1])])
for x, y in zip(a, a[1:]):
res = np.insert(res, -1, np.array(np.arange(x,y,(y-x)/4)))
print(res)
#=> [1. 1.75 2.5 3.25 4. 3.5 3. 2.5 2. ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With