1

I have a np.ndarray with the shape (24, 3). I want to flatten this array but in a rathor unusual way. I would like to have [0:8, 0] then [0:8, 1] then [0:8, 2] then [8:16, 0] and so on.

Of course i could do it the brute force way but maybe there is a more elegant and efficient solution to this problem.

new_array = np.array([])
np.append(new_array, old_array[0:8, 0])
np.append(new_array, old_array[0:8, 1])
np.append(new_array, old_array[0:8, 2])

np.append(new_array, old_array[8:16, 0])
np.append(new_array, old_array[8:16, 1])
np.append(new_array, old_array[8:16, 2])

np.append(new_array, old_array[16:24, 0])
np.append(new_array, old_array[16:24, 1])
np.append(new_array, old_array[16:24, 2])
slin
  • 411
  • 3
  • 8

1 Answers1

1

Reshape, permute and reshape -

n = 8 # cut length along first axis
new_array = old_array.reshape(-1,n,old_array.shape[1]).swapaxes(1,2).ravel()
Divakar
  • 218,885
  • 19
  • 262
  • 358