Search code examples
numpynumpy-ndarray

How to rearrange a 3d array from shape (nx, ny, nz) to shape (nz, nx, ny)?


I wonder if there is a more pythonic way (without the for loop) of obtaining a 3d array made of transversal (axes=2) slices of another 3d array such as from

A = np.array([[[1,1,1], [2,2,2]], [[3,3,3],[4,4,4]]])

I want to obtain

B=[[[1,2],[3,4]],[[1,2],[3,4]], [[1,2],[3,4]]]

Here's a minimal code that does that

import numpy as np
A = np.array([[[1,1,1], [2,2,2]], [[3,3,3],[4,4,4]]])
B=np.ndarray((3, 2, 2))
for i in range(3):
  B[i] = A[:,:,i]
print('B=', B)

Straightforward reshape such as A.reshape(3,2,2) doesn't work as intended.


Solution

  • transpose takes parameters that let you rearrange the axes:

    For example:

    In [61]: x=np.arange(24).reshape(2,3,4)
    
    In [62]: y = x.transpose(1,2,0); y.shape
    Out[62]: (3, 4, 2)
    

    In your case, (2,0,1) is probably the right one.