Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose 3D Numpy Array

Trying to transpose each numpy array in my numpy array.

Here is an example of what I want:

A:

 [[[ 1  2  3]
   [ 4  5  6]]

  [[ 7  8  9]
   [10 11 12]]]

A Transpose:

 [[[ 1  4]
   [ 2  5]
   [ 3  6]]

  [[ 7  10]
   [ 8  11]
   [ 9  12]]]

Tried doing this using np.apply_along_axis function but was not getting the correct results.I am trying to apply this to a very large array and any help would be greatly appreciated!

A=np.arange(1,13).reshape(2,2,3)
A=np.apply_along_axis(np.transpose, 0, A)
like image 885
MrClean Avatar asked Dec 19 '22 00:12

MrClean


2 Answers

You need to swap the second and third axises, for which you can use either np.swapaxes:

A.swapaxes(1,2)

#array([[[ 1,  4],
#        [ 2,  5],
#        [ 3,  6]],

#       [[ 7, 10],
#        [ 8, 11],
#        [ 9, 12]]])

or transpose:

A.transpose(0,2,1)

#array([[[ 1,  4],
#        [ 2,  5],
#        [ 3,  6]],

#       [[ 7, 10],
#        [ 8, 11],
#        [ 9, 12]]])
like image 54
Psidom Avatar answered Mar 08 '23 22:03

Psidom


For the sake of completeness, there are is also moveaxis which replaces the deprecated rollaxis:

>>> np.rollaxis(A, 2, 1)
array([[[ 1,  4],
        [ 2,  5],
        [ 3,  6]],

       [[ 7, 10],
        [ 8, 11],
        [ 9, 12]]])
>>> np.moveaxis(A, 2, 1)
array([[[ 1,  4],
        [ 2,  5],
        [ 3,  6]],

       [[ 7, 10],
        [ 8, 11],
        [ 9, 12]]])
like image 43
Paul Panzer Avatar answered Mar 08 '23 23:03

Paul Panzer