Search code examples
pythonnumpytranspose

How to transpose first 2 dimensions in 3D array


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.


Solution

  • You can use the .transpose() function.

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

    means swap the first and the second axis.