2

I have this array:

my_array = np.arange(1216800).reshape(2, 100, 78, 78)

The shape now is: (2, 100, 78, 78) and I want to reorder to : (100, 78, 78, 2).

I tried something like:

my_array[:, :, 2, :], my_array[:, :, :,  3] = my_array[:, :, :, 3], my_array[:, :, 2, :].copy()

to swap first those columns, but I am receiving the same array.

I saw this but whatever I try, I am having the same array.

George
  • 5,808
  • 15
  • 83
  • 160

2 Answers2

4

Use moveaxis to move the first axis (0) to the end (-1):

out = np.moveaxis(my_array, 0, -1)

out.shape
# (100, 78, 78, 2)
mozway
  • 194,879
  • 13
  • 39
  • 75
3

Here is the code that you want:

import numpy as np

my_array = np.arange(1216800).reshape(2, 100, 78, 78)
reordered_array = np.transpose(my_array, (1, 2, 3, 0))

print(reordered_array.shape)  # Output: (100, 78, 78, 2)
Omid Roshani
  • 1,083
  • 4
  • 15
  • 4
    The transpose is fine, but you really shouldn't use the nested loop approach, this makes no sense in numpy. – mozway Jul 17 '23 at 11:31
  • And a highly nested loop would not be considered Pythonic. You could try and say it's pure Python, but considering the array is not pure Python in the first place, even that would be inaccurate. – jared Jul 17 '23 at 14:14