MrClean
MrClean

Reputation: 1460

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)

Upvotes: 6

Views: 6602

Answers (3)

Paul Panzer
Paul Panzer

Reputation: 53029

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]]])

Upvotes: 3

anon01
anon01

Reputation: 11171

The transformation you seek:

A = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
solution = np.array([A[0].T,A[1].T]) 

Upvotes: 0

akuiper
akuiper

Reputation: 214927

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]]])

Upvotes: 11

Related Questions