1

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!

1
  • Heard of np.reshape? Commented Oct 31, 2017 at 20:29

2 Answers 2

3

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

+1, Nice trick using the -1, the documentation mentioned "One shape dimension can be -1.", and this is a clever implementation of that.
2

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.

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.