Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply linspace between each element in numpy vector?

Tags:

python

numpy

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?

like image 955
naseefo Avatar asked Sep 05 '25 03:09

naseefo


2 Answers

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.  ])
like image 131
Psidom Avatar answered Sep 07 '25 21:09

Psidom


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.  ]
like image 30
iGian Avatar answered Sep 07 '25 20:09

iGian