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?
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)
There are a few ways, but transpose() is probably the easiest:
array.transpose(2,0,1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With