Divide numpy array into multiple arrays using indices array (Python)

Viewed 2873

I have an array:

a = [1, 3, 5, 7, 29 ... 5030, 6000]

This array gets created from a previous process, and the length of the array could be different (it is depending on user input).

I also have an array:

b = [3, 15, 67, 78, 138]

(Which could also be completely different)

I want to use the array b to slice the array a into multiple arrays.

More specifically, I want the result arrays to be:

array1 = a[:3]
array2 = a[3:15]
...
arrayn = a[138:]

Where n = len(b).

My first thought was to create a 2D array slices with dimension (len(b), something). However we don't know this something beforehand so I assigned it the value len(a) as that is the maximum amount of numbers that it could contain.

I have this code:

 slices = np.zeros((len(b), len(a)))

 for i in range(1, len(b)):
     slices[i] = a[b[i-1]:b[i]]

But I get this error:

ValueError: could not broadcast input array from shape (518) into shape (2253412)
3 Answers
Related