dayum dayum - 17 days ago 8
Python Question

Creating NumPy ranges for multiple start and stop values

I need to create a 2D array where each row may start and end with a different number. Assume that first and last element of each row is given and all other elements are just interpolated according to length of the rows In a simple case let's say I want to create a 3X3 array with same start at 0 but different end given by W below:

array([[ 0., 1., 2.],
[ 0., 2., 4.],
[ 0., 3., 6.]])


Is there a better way to do this than the following:

D=np.ones((3,3))*np.arange(0,3)
D=D/D[:,-1]
W=np.array([2,4,6]) # last element of each row assumed given
Res= (D.T*W).T

Answer

Here's an approach using broadcasting -

def create_ranges(start, stop, N):
    steps = (1.0/(N-1)) * (stop - start)
    return steps[:,None]*np.arange(N) + start[:,None]

Sample run -

In [122]: # Setup start, stop for each row and no. of elems in each row
     ...: start = np.array([1,4,2])
     ...: stop = np.array([6,7,6])
     ...: N = 5
     ...: 

In [123]: create_ranges(start, stop, 5)
Out[123]: 
array([[ 1.  ,  2.25,  3.5 ,  4.75,  6.  ],
       [ 4.  ,  4.75,  5.5 ,  6.25,  7.  ],
       [ 2.  ,  3.  ,  4.  ,  5.  ,  6.  ]])