2

I wanted to create a 3D NumPy array with sequential numbers like so:

[[[11 27 43]
  [12 28 44]
  [13 29 45]
  [14 30 46]]

 [[15 31 47]
  [16 32 48]
  [17 33 49]
  [18 34 50]]

 [[19 35 51]
  [20 36 52]
  [21 37 53]
  [22 38 54]]

 [[23 39 55]
  [24 40 56]
  [25 41 57]
  [26 42 58]]]

I did this: A = np.arange(11, 59).reshape((4, 4, 3)) but I got this instead:

[[[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 48 49]
  [50 51 52]
  [53 54 55]
  [56 57 58]]]

So it's not the sequence that I wanted. I had done some additional steps to get the correct 3D array. First, I shaped the numbers into a 2D array: A = np.arange(11, 59).reshape((-1, 4)) to get this:

[[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 48 49 50]
 [51 52 53 54]
 [55 56 57 58]]

Then, I splitted and stacked the 2D array and got the 3D array that I wanted: A = np.dstack(np.vsplit(A, 3))

[[[11 27 43]
  [12 28 44]
  [13 29 45]
  [14 30 46]]

 [[15 31 47]
  [16 32 48]
  [17 33 49]
  [18 34 50]]

 [[19 35 51]
  [20 36 52]
  [21 37 53]
  [22 38 54]]

 [[23 39 55]
  [24 40 56]
  [25 41 57]
  [26 42 58]]]

Now I'm wondering if there is a more elegant and straightforward way to achieve the same result. Thanks you.

Rendicahya
  • 4,205
  • 7
  • 36
  • 56

1 Answers1

6

Get the ranged array, reshape and then permute axes -

np.arange(11, 59).reshape(3,4,4).transpose(1,2,0)

Another way to permute axes would be to use np.moveaxis -

np.moveaxis(np.arange(11, 59).reshape(3,4,4),0,2)

Discussion : A general intuition to solving such problems.

Divakar
  • 218,885
  • 19
  • 262
  • 358