2

I have a massive array but for illustration I am using an array of size 14. I have another list which contains 2, 3, 3, 6. How do I efficiently without for look create a list of new arrays such that:

import numpy as np
A = np.array([1,2,4,5,7,1,2,4,5,7,2,8,12,3]) # array with 1 axis
subArraysizes = np.array( 2, 3, 3, 6 ) #sums to number of elements in A
B = list()
B[0] = [1,2]
B[1] = [4,5,7]
B[2] = [1,2,4]
B[3] = [5,7,2,8,12,3]

i.e. select first 2 elements from A store it in B, select next 3 elements of A store it in B and so on in the order it appears in A.

1 Answer 1

3

You can use np.split -

B = np.split(A,subArraysizes.cumsum())[:-1]

Sample run -

In [75]: A
Out[75]: array([ 1,  2,  4,  5,  7,  1,  2,  4,  5,  7,  2,  8, 12,  3])

In [76]: subArraysizes
Out[76]: array([2, 3, 3, 6])

In [77]: np.split(A,subArraysizes.cumsum())[:-1]
Out[77]: 
[array([1, 2]),
 array([4, 5, 7]),
 array([1, 2, 4]),
 array([ 5,  7,  2,  8, 12,  3])]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.