How to use numpy.arange with two other arrays as the start and stop parameter?

Question:

I want to build a 2D-array where the first dimension has the same length as two other arrays and the second dimension is an array created by numpy.arange and based on every element of the other two arrays, where one array defines the start parameter and the second array defines the stop parameter-1.

Let me give an example:

arr_1 = array([0, 0, 0, 1, 2, 3, 4])
arr_2 = array([0, 1, 2, 3, 4, 5, 6])

I’m trying to create a resulting array like this:

res_arr = array([[0], [0, 1], [0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]])

Can this be done with numpy ?

Asked By: Steven01123581321

||

Answers:

You can do this by using zip and list comprehension

res_arr = [np.arange(start, stop + 1) for start, stop in zip(arr_1, arr_2)]
Answered By: steflbert