Ehsan Khaveh
Ehsan Khaveh

Reputation: 1454

Python - Rearrange elements in a 3D array

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

Upvotes: 2

Views: 3247

Answers (3)

Hugo G
Hugo G

Reputation: 16496

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

Upvotes: 2

alexblae
alexblae

Reputation: 746

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

Upvotes: 1

Divakar
Divakar

Reputation: 221584

Use np.transpose -

a.transpose(2,0,1)

Or use np.rollaxis -

np.rollaxis(a,2,0) # Or np.rollaxis(a,-1,0)

Upvotes: 4

Related Questions