Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate over numpy array to get sub-arrays

Given the following numpy array:

arr = np.array([0, 1, 2, 3, 4, 5])

what iterable would return sub-arrays of length x from arr? (Given that len(arr) is a multiple of x)

x = 2
sub_arrays = [sub_arr for sub_arr in iterable(arr, x)]

sub_arrays = [ np.ndarray( [0, 1] ), np.ndarray( [2, 3] ), np.ndarray( [4, 5] ) ]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know that array slicing is possible with start, stop, and step arguments, but that returns individual elements:

x = 2
sub_elements = [sub_elem for sub_elem in arr[::x]]

sub_elements = [0, 2, 4]

>Solution :

you should use np.array_split

arr = np.array([0, 1, 2, 3, 4, 5])
x = 2
sub_elements = np.array_split(arr, len(arr)/x)
[ array([0,1]), array([2,3]), array([4,5]) ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading