1

I want to do the equivalent of permute.m in MATLAB for an array in Python.

For example: A is a 4D array with the shape (50,50,3,100) that I want to make (100,50,50,3). In MATLAB this can be done:

B = permute(A,[4,1,2,3])

How to do this in Python?

gboffi
  • 22,939
  • 8
  • 54
  • 85
jwm
  • 4,832
  • 10
  • 46
  • 78

2 Answers2

4

If what you want is to transpose your array, Numpy arrays have a .transpose method, you have just to remember that Python counts from zero

b = a.transpose((3,0,1,2))

(note that the method takes a single argument, a tuple describing the permutation of the axes).

gboffi
  • 22,939
  • 8
  • 54
  • 85
  • I have used small letters because it is customary to reserve capitals to `class`es and, to a lesser extent, to constants. – gboffi Oct 31 '18 at 15:59
0

If you use numpy you can use swapaxes

numpy.swapaxes(a, axis1, axis2)


# equivalent to [4,1,2,3]
B = A.swapaxes(3,0).swapaxes(1,3).swapaxes(2,3)

or transpose

B = A.transpose((3,0,1,2))

Otherwise you can use np.moveaxis

B = A.moveaxis([0, 1, 2, 3], [-3, -2, -1, -4])
Gabriel M
  • 1,486
  • 4
  • 17
  • 25