Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 783
pavlos163 Avatar asked Nov 08 '25 23:11

pavlos163


2 Answers

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])]
like image 176
Psidom Avatar answered Nov 10 '25 14:11

Psidom


b.insert(0,0)
result = []
for i in range(1,len(b)):
    sub_list = a[b[i-1]:b[i]]
    result.append(sub_list)
result.append(a[b[-1]:])
like image 22
Bohdan Avatar answered Nov 10 '25 12:11

Bohdan



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!