I have a 5D array 'a', of size (3,2,2,2,2).
import numpy as np
a = np.arange(48).reshape(3,2,2,2,2)
a[0,0,0]:
array([[0, 1],
[2, 3]])
What I want to do is rotate this 5D array by 180 degrees, but only in the last two dimensions, without their positions changed. So output[0,0,0] should look like this:
out[0,0,0]:
array([[3, 2],
[1, 0]])
What I have tried:
out = np.rot90(a, 2)
out[0,0,0]:
array([[40, 41],
[42, 43]])
The rot90
function apparently rotates the whole array.
Note: I want to avoid using for loops if possible
To rotate the last two axes 180 degrees, pass axes=(-2, -1)
to np.rot90
:
>>> a180 = np.rot90(a, 2, axes=(-2, -1))
>>> a180[0, 0, 0]
array([[3, 2],
[1, 0]])
If your version of NumPy does not have the axes
parameter with np.rot90
, there are alternatives.
One way is with indexing:
a180 = a[..., ::-1, ::-1]
rot90
flips the first two axes of the array, therefore to use it you'd need to transpose (to reverse the axes), rotate, and transpose back again. For example:
np.rot90(a.T, 2).T
If I understood the question correctly, you could reverse the arrangement of the elements along the last two axes, like so -
a[:,:,::-1,::-1]
You can also reshape to a 2D array merging the last two axes as the last axis, then reverse elements along it and reshape back, like so -
a.reshape(-1,np.prod(a.shape[-2:]))[:,::-1].reshape(a.shape)
Sample run -
In [141]: a[0][0]
Out[141]:
array([[57, 64, 69],
[41, 28, 89]])
In [142]: out1 = a[:,:,::-1,::-1]
In [143]: out2 = a.reshape(-1,np.prod(a.shape[-2:]))[:,::-1].reshape(a.shape)
In [144]: out1[0][0]
Out[144]:
array([[89, 28, 41],
[69, 64, 57]])
In [145]: out2[0][0]
Out[145]:
array([[89, 28, 41],
[69, 64, 57]])
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