Skip to content Skip to sidebar Skip to footer

Change Shape Of Nparray

import numpy as np ​ image1 = np.zeros((120, 120)) image2 = np.zeros((120, 120)) image3 = np.zeros((120, 120)) ​ pack1 = np.array([image1,image2,image3]) pack2 = np.array([imag

Solution 1:

Use np.rollaxis to move (OK, roll) a single axis to a specified position:

>>>a.shape
(2, 3, 11, 11)
>>>np.rollaxis(a, 0, 4).shape
(3, 11, 11, 2)

Here the syntax is "roll the zeroth axis so that it becomes the 4th in the new array".

Notice that rollaxis creates a view and does not copy:

>>> np.rollaxis(a, 0, 4).base is a
True

An alternative (and often more readable) way would be to use the fact that np.transpose accepts a tuple of where to place the axes. Observe:

>>>np.transpose(a, (1, 2, 3, 0)).shape
(3, 11, 11, 2)
>>>np.transpose(a, (1, 2, 3, 0)).base is a
True

Here the syntax is "permute the axes so that what was the zeroth axis in the original array becomes the 4th axis in the new array"

Solution 2:

You can transpose your packs

pack1 = np.array([image1,image2,image3]).T
pack2 = np.array([image1,image2,image3]).T

and the result has your desired shape.

Solution 3:

The (relatively) new stack function gives more control that np.array on how arrays are joined.

Use stack to join them on a new last axis:

In [24]: pack1=np.stack((image1,image2,image3),axis=2)
In [25]: pack1.shape
Out[25]: (120, 120, 3)
In [26]: pack2=np.stack((image1,image2,image3),axis=2)

then join on a new first axis (same as np.array()):

In [27]: result=np.stack((pack1,pack2),axis=0)
In [28]: result.shape
Out[28]: (2, 120, 120, 3)

Post a Comment for "Change Shape Of Nparray"