Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Transpose each element in a 3D np array

Tags:

python

numpy

Given a 3D array a, I want to call np.tranpose on each of the element in its first index.
For example, given the array:

array([[[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]],

       [[2, 2, 2, 2],
        [2, 2, 2, 2],
        [2, 2, 2, 2]],

       [[3, 3, 3, 3],
        [3, 3, 3, 3],
        [3, 3, 3, 3]])

I want:

array([[[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]],

       [[2, 2, 2],
        [2, 2, 2],
        [2, 2, 2],
        [2, 2, 2]],

       [[3, 3, 3],
        [3, 3, 3],
        [3, 3, 3],
        [3, 3, 3]]])

Essentially I want to transpose each element inside the array. I tried to reshape it but I can't find a good way of doing it. Looping through it and calling transpose on each would be too slow. Any advice?

like image 339
Discombobulous Avatar asked Nov 09 '16 04:11

Discombobulous


People also ask

How do you transpose an array in NP?

NumPy Matrix transpose() - Transpose of an Array in Python The transpose of a matrix is obtained by moving the rows data to the column and columns data to the rows. If we have an array of shape (X, Y) then the transpose of the array will have the shape (Y, X).

What is a transpose of a 3 dimensional matrix?

The transpose of a matrix is simply a flipped version of the original matrix. We can transpose a matrix by switching its rows with its columns. We denote the transpose of matrix A by AT. For example, if A=[123456] then the transpose of A is AT=[142536].

What is difference between .T and transpose () in NumPy?

T and the transpose() call both return the transpose of the array. In fact, . T return the transpose of the array, while transpose is a more general method_ that can be given axes ( transpose(*axes) , with defaults that make the call transpose() equivalent to . T ).

How do I flip columns and rows in NumPy?

To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.


1 Answers

You can use the built-in numpy transpose method and directly specify the axes to transpose

>>> a = np.array([[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
                  [[2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2]],
                  [[3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3]]])

>>> print(a.transpose((0, 2, 1)))

[[[1 1 1]
  [1 1 1]
  [1 1 1]
  [1 1 1]]

 [[2 2 2]
  [2 2 2]
  [2 2 2]
  [2 2 2]]

 [[3 3 3]
  [3 3 3]
  [3 3 3]
  [3 3 3]]]
like image 56
Chris Mueller Avatar answered Oct 06 '22 00:10

Chris Mueller