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

arrays, numpy, python

Solution

You can use numpy.split:

np.split(a, b)

Example:

np.split(np.arange(10), [3,5])
# [array([0, 1, 2]), array([3, 4]), array([5, 6, 7, 8, 9])]

Problem

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) ```

Original source