4
$\begingroup$

I have a 3D matrix like this:

array([[[ 0,  1],
      [ 2,  3]],

      [[ 4,  5],
      [ 6,  7]],

      [[ 8,  9],
      [10, 11]],

      [[12, 13],
      [14, 15]]])

and would like to stack them in a grid format, ending up with:

 array([[ 0,  1],
        [ 2,  3],
        [ 4,  5],
        [ 6,  7],
        [ 8,  9],
        [10, 11],
        [12, 13],
        [14, 15]])

Currently, I'm using numpy as a library.

$\endgroup$
5
$\begingroup$

I suggest you to visit this link also for this case would work np.reshape((-1,2))

|improve this answer|||||
$\endgroup$
  • 1
    $\begingroup$ This works nicely! the exactly syntax would be arr.reshape((-1, 2)), and the link seems to be wrong, reshape is docs.scipy.org/doc/numpy-1.15.0/reference/generated/…. @GrozaiL, but this (-1, 2) feels like magic for me, could you explain how it works? Thanks! $\endgroup$ – Indominus Jan 14 '19 at 3:56
0
$\begingroup$

The numpy.reshape() allows you to do reshaping in multiple ways.

It usually unravels the array row by row and then reshapes to the way you want it.

If you want it to unravel the array in column order you need to use the argument order='F'

Let's say the array is a. For the case above, you have a (4, 2, 2) ndarray

numpy.reshape(a, (8, 2)) will work.

In the general case of a (l, m, n) ndarray:

numpy.reshape(a, (l*m, n)) should be used.

Or, numpy.reshape(a, (a.shape[0]*a.shape[1], a.shape[2])) should be used.

For more info numpy.reshape()

|improve this answer|||||
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.