4

I have a 1 x 2 x 3 array:

>>> a = np.array([[[1,2,3],[4,5,6]]])
>>> a
array([[[1, 2, 3],
        [4, 5, 6]]])
>>> a.shape
(1, 2, 3)

I want to reshape it to (3,1,2), but so that the elements along original dim 3 are now along dim 1. I want the result to look like this:

>>> new_a
array([[[1, 4]],
       [[2, 5]],
       [[3, 6]]])

and when I just use reshape, I get the the right shape, but the elements are in the same order, not what I want:

>>> a.reshape((3,1,2))
array([[[1, 2]],
       [[3, 4]],
       [[5, 6]]])

How can I achieve this?

3 Answers 3

3

Simply use np.transpose -

a.transpose(2,0,1)

Sample run -

In [347]: a
Out[347]: 
array([[[1, 2, 3],
        [4, 5, 6]]])

In [348]: a.transpose(2,0,1)
Out[348]: 
array([[[1, 4]],

       [[2, 5]],

       [[3, 6]]])

Alternatively :

With np.moveaxis -

np.moveaxis(a,2,0)

With np.rollaxis -

np.rollaxis(a,2,0)
Sign up to request clarification or add additional context in comments.

Comments

1

There are a few ways, but transpose() is probably the easiest:

array.transpose(2,0,1)

Comments

0
import einops
einops.rearrange(x, 'x y z -> z x y')

And better use some meaningful axes names instead of x, y, z (like width, height, etc.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.