8

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?

5
  • 1
    Read the transpose docs. It takes a parameter. Something like a.transpose([0,2,1]).
    – hpaulj
    Nov 9, 2016 at 4:39
  • Is your array just filled with 1,2 and 3 as you show? If so, simple reshape will work: arr.reshape(3,4,3)
    – Julien
    Nov 9, 2016 at 4:44
  • You example is ambiguous. It could be a tranpose or a reshape case.
    – hpaulj
    Nov 9, 2016 at 4:58
  • @julien In a general case in which matrix elements can be arbitrary, reshape doesn't work right? It is not the expected output of transposing a matrix.
    – Francis
    Aug 7, 2017 at 10:37
  • 1
    @Francis yes, this would work only on the example given by OP, not in general case: reshape on [[1,2,3],[4,5,6]] will give [[1,2],[3,4],[5,6]] while transpose will give [[1,4],[2,5],[3,6]]. If input is [[1,1,1],[1,1,1]] like in example there would be no difference though.
    – Julien
    Aug 8, 2017 at 0:52

1 Answer 1

15

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]]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.