Home > Enterprise >  How to transpose first 2 dimensions in 3D array
How to transpose first 2 dimensions in 3D array

Time:03-16

How do I transpose the first 2 dimensions of a 3D array 'matrix?

matrix = np.random.rand(2,3,4)

In the third dimensions I want to swap 'rows' with 'columns', preferably without a loop.

CodePudding user response:

You can use the .transpose() function.

matrix = matrix.transpose(1, 0, 2)

means swap the first and the second axis.

CodePudding user response:

You can use swapaxes:

matrix2 = matrix.swapaxes(0,1)

example:

# input
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

# output
array([[[ 0,  1,  2,  3],
        [12, 13, 14, 15]],

       [[ 4,  5,  6,  7],
        [16, 17, 18, 19]],

       [[ 8,  9, 10, 11],
        [20, 21, 22, 23]]])
  • Related