2

I have the following Numpy array of shape (4, 4, 3):

a = [[[ 0  1  2]
      [ 3  4  5]
      [ 6  7  8]
      [ 9 10 11]]

      [[12 13 14]
       [15 16 17]
       [18 19 20]
       [21 22 23]]

      [[24 25 26]
       [27 28 29]
       [30 31 32]
       [33 34 35]]

      [[36 37 38]
       [39 40 41]
       [42 43 44]
       [45 46 47]]]

I am looking for an elegant solution to re-arrange the elements in that array to get the following 3D array of shape (3, 4, 4):

a_new = [[[ 0  3  6  9]
          [12 15 18 21]
          [24 27 30 33]
          [36 39 42 45]]

         [[ 1  4  7 10]
          [13 16 19 22]
          [25 28 31 34]
          [37 40 43 46]]

         [[ 2  5  8 11]
          [14 17 20 23]
          [26 29 32 35]
          [38 41 44 47]]]
1
  • So basically you want to put all elements from all lists into one and then split them into three step-wise? Commented Jan 13, 2017 at 14:59

3 Answers 3

4

Use np.transpose -

a.transpose(2,0,1)

Or use np.rollaxis -

np.rollaxis(a,2,0) # Or np.rollaxis(a,-1,0)
Sign up to request clarification or add additional context in comments.

Comments

2

In case somebody asks the same question for pure Python:

mylist = [[[1,2,3], [4,5,6]], [[7,8,9], [10, 11, 12]]]
flat = sum(sum(mylist, []), [])
groups = 3
print [flat[r::groups] for r in range(groups)]

[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

Comments

1

The fastest way I can think of is to use numpy's swapaxes function in combination with the transpose function.

anew=np.swapaxes(a,0,1).T

5 Comments

This works too but np.transpose seems to be much faster
Interesting. You would think that array.T is just calling np.transpose on self, but apparently not. I need to test this some other time.
Okay. I had 0.00405ms for array.T and 0.00095ms for np.transpose. Tested it on a bigger array of shape (256, 256, 3)
@Ehsan With np.swapaxes(a,0,1).T we are making two passes of permuting axes, once with the swapaxes and then with the transpose (.T), whereas a.transpose(2,0,1) is just one pass of permuting axes. Hence, the performance difference.
@Divakar that makes sense. I totally missed that. thanks :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.