Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reshape numpy array with reorder?

Tags:

python

numpy

I have a 1 x 2 x 3 array:

>>> a = np.array([[[1,2,3],[4,5,6]]])
>>> a
array([[[1, 2, 3],
        [4, 5, 6]]])
>>> a.shape
(1, 2, 3)

I want to reshape it to (3,1,2), but so that the elements along original dim 3 are now along dim 1. I want the result to look like this:

>>> new_a
array([[[1, 4]],
       [[2, 5]],
       [[3, 6]]])

and when I just use reshape, I get the the right shape, but the elements are in the same order, not what I want:

>>> a.reshape((3,1,2))
array([[[1, 2]],
       [[3, 4]],
       [[5, 6]]])

How can I achieve this?

like image 532
Christopher Brown Avatar asked Oct 20 '25 15:10

Christopher Brown


2 Answers

Simply use np.transpose -

a.transpose(2,0,1)

Sample run -

In [347]: a
Out[347]: 
array([[[1, 2, 3],
        [4, 5, 6]]])

In [348]: a.transpose(2,0,1)
Out[348]: 
array([[[1, 4]],

       [[2, 5]],

       [[3, 6]]])

Alternatively :

With np.moveaxis -

np.moveaxis(a,2,0)

With np.rollaxis -

np.rollaxis(a,2,0)
like image 138
Divakar Avatar answered Oct 24 '25 10:10

Divakar


There are a few ways, but transpose() is probably the easiest:

array.transpose(2,0,1)
like image 29
Alec Avatar answered Oct 24 '25 11:10

Alec