Argo
Argo

Reputation: 103

Split Numpy array into equal-length sub-arrays

I have a very huge numpy array like this:

np.array([1, 2, 3, 4, 5, 6, 7 , ... , 12345])

I need to create subgroups of n elements (in the example n = 3) in another array like this:

np.array([[1, 2, 3],[4, 5, 6], [6, 7, 8], [...],  [12340, 12341, 12342], [12343, 12344, 12345]])

I did accomplish that using normal python lists, just appending the subgroups to another list. But, I'm having a hard time trying to do that in numpy.

Any ideas how can I do that?

Thanks!

Upvotes: 1

Views: 5293

Answers (2)

Joe Iddon
Joe Iddon

Reputation: 20414

You can use np.reshape():

From the documentation (link in title):

numpy.reshape(a, newshape, order='C')

Gives a new shape to an array without changing its data.

Here is an example of how you can apply it to your situation:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 12345])
>>> a.reshape((int(len(a)/3), 3))
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 12345]], dtype=object)

Note that obviously, the length of the array (len(a)) has to be a multiple of 3 to be able to reshape it into a 2-dimensional numpy array, because they must be rectangular.

Upvotes: 2

1''
1''

Reputation: 27095

You can use np.reshape(-1, 3), where the -1 means "whatever's left".

>>> array = np.arange(1, 12346)
>>> array
array([    1,     2,     3, ..., 12343, 12344, 12345])
>>> array.reshape(-1, 3)
array([[    1,     2,     3],
       [    4,     5,     6],
       [    7,     8,     9],
       ..., 
       [12337, 12338, 12339],
       [12340, 12341, 12342],
       [12343, 12344, 12345]])

Upvotes: 3

Related Questions