Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolate values row-wise for 2D Numpy array

Tags:

python

numpy

I have two numpy arrays:

x = np.array([1,2,3,4,5])
y = np.array([10,20,30,40,50])

What I try to get is something like this:

array([[  1.  ,   3.25,   5.5 ,   7.75,  10.  ],
       [  2.  ,   6.5 ,  11.  ,  15.5 ,  20.  ],
       [  3.  ,   9.75,  16.5 ,  23.25,  30.  ],
       [  4.  ,  13.  ,  22.  ,  31.  ,  40.  ],
       [  5.  ,  16.25,  27.5 ,  38.75,  50.  ]])

My approach is not very Numpy like and needs improvement (getting rid of the for-loop) for very large arrays:

myarray = np.zeros((5,5))
for idx in np.arange(5):
    myarray[idx,:] = np.linspace(x[idx], y[idx], 5)

What would be a good approach to do this in Numpy? Would it be better to generate the myarray this way and then manipulate it?

myarray = np.zeros((5,5))
myarray[:,0] = x
myarray[:,-1] = y

array([[  1.,   0.,   0.,   0.,  10.],
       [  2.,   0.,   0.,   0.,  20.],
       [  3.,   0.,   0.,   0.,  30.],
       [  4.,   0.,   0.,   0.,  40.],
       [  5.,   0.,   0.,   0.,  50.]])
like image 333
HyperCube Avatar asked Oct 18 '25 13:10

HyperCube


2 Answers

This broadcasting trickery works:

>>> x = np.array([1,2,3,4,5])
>>> y = np.array([10,20,30,40,50])
>>> z = np.linspace(0, 1, 5)
>>> z[None, ...] * (y[..., None] - x[..., None]) + ( x[..., None])
array([[  1.  ,   3.25,   5.5 ,   7.75,  10.  ],
       [  2.  ,   6.5 ,  11.  ,  15.5 ,  20.  ],
       [  3.  ,   9.75,  16.5 ,  23.25,  30.  ],
       [  4.  ,  13.  ,  22.  ,  31.  ,  40.  ],
       [  5.  ,  16.25,  27.5 ,  38.75,  50.  ]])
>>> 
like image 79
YXD Avatar answered Oct 21 '25 01:10

YXD


This is another solution using np.nditer for iterating over arrays:

>>> import numpy as np
>>> n = 5
>>> x = np.array([1,2,3,4,5])
>>> y = np.array([10,20,30,40,50])
>>> z = np.empty(shape=(n, x.shape[0]), dtype=float)

>>> for k, (i,j) in enumerate(np.nditer([x,y])):
        z[k,:] = np.linspace(i,j,n)
>>> z
[[  1.     3.25   5.5    7.75  10.  ]
 [  2.     6.5   11.    15.5   20.  ]
 [  3.     9.75  16.5   23.25  30.  ]
 [  4.    13.    22.    31.    40.  ]
 [  5.    16.25  27.5   38.75  50.  ]] 
like image 25
jabaldonedo Avatar answered Oct 21 '25 02:10

jabaldonedo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!