-1

I want to reshape array of shape (2, *(x, y)) to (1, *(x,y), 2) while preserving the values of (x, y)?

(2, *(x,y)) where 2 represents the frames of game screen with (x, y) being an array with pixel values. I wish to convert it into an array of shape of (1, *(x, y), 2), such that the number 2 still represents the frame index, while (x,y) array value is preserved. 1 will be used to index the batch for training the neural network.

numpy.reshape(1, *(x,y), 2) doesn't preserve the (x,y) array.

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29

1 Answers1

0

Use numpy.transpose(), e.g.:

import numpy as np

arr = np.arange(2 * 3 * 4).reshape((2, 3, 4))
arr.shape
# (2, 3, 4)

arr.transpose(1, 2, 0).shape
# (3, 4, 2)

new_arr = arr.transpose(1, 2, 0)[None, ...]
new_arr.shape
# (1, 3, 4, 2)

# the `(3, 4)` array is preserved:
arr.transpose(1, 2, 0)[:, :, 0] 
# array([[ 0,  1,  2,  3],
#        [ 4,  5,  6,  7],
#        [ 8,  9, 10, 11]])

arr[0, :, :]
# array([[ 0,  1,  2,  3],
#        [ 4,  5,  6,  7],
#        [ 8,  9, 10, 11]])
norok2
  • 25,683
  • 4
  • 73
  • 99
  • what does [None, ...] mean? And also what does the three dots represent? – Azlaan Mustafa Samad Aug 13 '19 at 12:21
  • That is equivalent to [`np.newaxis`](https://stackoverflow.com/questions/29241056/how-does-numpy-newaxis-work-and-when-to-use-it), more on this [in the official docs](https://docs.scipy.org/doc/numpy-1.17.0/reference/arrays.indexing.html). – norok2 Aug 13 '19 at 12:50
  • Okay so it is used to add new axis to the array, So do I need to put the three dots in the code as well. I am very new to coding so it might be a silly question. Bear with me :) – Azlaan Mustafa Samad Aug 13 '19 at 12:55
  • Yes, (all code comes for a reason). The three dots are a built-in Python object called [`Ellipsis`](https://stackoverflow.com/questions/118370/how-do-you-use-the-ellipsis-slicing-syntax-in-python). – norok2 Aug 13 '19 at 12:59