Alex Van de Kleut
Alex Van de Kleut

Reputation: 110

How to specify order during np.reshape

I have a numpy ndarray of shape (t, n, h, w, c). I want to partially flatten it to get an ndarray of shape (t*n, h, w, c). However, I want to be able to specify the order that this happens in. Specifically, I want it in 'n-major order'.

Let's say I have an array A with A.shape = (128, 16, 160, 210, 3 and an array B with B.shape = (16, 128, 160, 210, 3). They are almost the same, except the first two dimensions are swapped.

Flattening B as follows groups the data the way I would like:

B = B.reshape(-1, *B.shape[2:])

B.shape = (2048, 160, 210, 3)

Flattening A gives an array of the same shape, but with data in a different order.

I have tried the following: A = np.moveaxis(A, 0, 1) A = A.reshape(-1, *A.shape[2:])

I can kind of get it to work doing A = np.asarray([A[:, i, ...] for i in range(n)]) where n is the length of the second dimension, but I feel like there is a more numpionic way of doing this.

I think that because moveaxis (and swapaxis) creates a view (which is supposed to change the traversal order) that the default order for flattening is based on the original ordering of the data.

How can I flatten A in the way that I would like?

Upvotes: 1

Views: 1365

Answers (1)

shivammittal99
shivammittal99

Reputation: 91

You can use X.reshape(t*n, h, w, c, order='F')

Eg.

>>> x = np.array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

>>> x.shape
(2, 3, 4) 

>>> x.reshape(2*3, 4, order='C')
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]])

>>> x.reshape(2*3, 4, order='F')
array([[ 0,  1,  2,  3],
       [12, 13, 14, 15],
       [ 4,  5,  6,  7],
       [16, 17, 18, 19],
       [ 8,  9, 10, 11],
       [20, 21, 22, 23]])

Upvotes: 1

Related Questions