Swapping the dimensions of a numpy array Swapping the dimensions of a numpy array arrays arrays

Swapping the dimensions of a numpy array


The canonical way of doing this in numpy would be to use np.transpose's optional permutation argument. In your case, to go from ijkl to klij, the permutation is (2, 3, 0, 1), e.g.:

In [16]: a = np.empty((2, 3, 4, 5))In [17]: b = np.transpose(a, (2, 3, 0, 1))In [18]: b.shapeOut[18]: (4, 5, 2, 3)


Please note: Jaime's answer is better. NumPy provides np.transpose precisely for this purpose.


Or use np.einsum; this is perhaps a perversion of its intended purpose, but the syntax is quite nice:

In [195]: A = np.random.random((2,4,3,5))In [196]: B = np.einsum('klij->ijkl', A)In [197]: A.shapeOut[197]: (2, 4, 3, 5)In [198]: B.shapeOut[198]: (3, 5, 2, 4)In [199]: import itertools as IT    In [200]: all(B[k,l,i,j] == A[i,j,k,l] for i,j,k,l in IT.product(*map(range, A.shape)))Out[200]: True


You could rollaxis twice:

>>> A = np.random.random((2,4,3,5))>>> B = np.rollaxis(np.rollaxis(A, 2), 3, 1)>>> A.shape(2, 4, 3, 5)>>> B.shape(3, 5, 2, 4)>>> from itertools import product>>> all(B[k,l,i,j] == A[i,j,k,l] for i,j,k,l in product(*map(range, A.shape)))True

or maybe swapaxes twice is easier to follow:

>>> A = np.random.random((2,4,3,5))>>> C = A.swapaxes(0, 2).swapaxes(1,3)>>> C.shape(3, 5, 2, 4)>>> all(C[k,l,i,j] == A[i,j,k,l] for i,j,k,l in product(*map(range, A.shape)))True