5D array rotation in the last 2 dimensions

I have a 5D array 'a', 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 180 degrees, but only in the last two dimensions, without changing their positions. Therefore, the output [0,0,0] should look like this:

 out[0,0,0]: array([[3, 2], [1, 0]]) 

What I tried:

 out = np.rot90(a, 2) out[0,0,0]: array([[40, 41], [42, 43]]) 

The rot90 function obviously rotates the entire array.

Note. I want to avoid using for loops if possible

+5
source share
2 answers

To rotate the last two axes 180 degrees, go 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 an axes parameter with np.rot90 , there are alternatives.

One way is to index:

 a180 = a[..., ::-1, ::-1] 

rot90 flips the first two axes of the array, so to use it you need to transpose (to rotate the axes), rotate and transpose again. For instance:

 np.rot90(aT, 2).T 
+2
source

If I understood the question correctly, you could change the arrangement of elements along the last two axes, for example:

 a[:,:,::-1,::-1] 

You can also convert to a 2D array by combining the last two axes as the last axis, then move the elements along it and change the shape back, for example:

 a.reshape(-1,np.prod(a.shape[-2:]))[:,::-1].reshape(a.shape) 

Run Example -

 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]]) 
+1
source

Source: https://habr.com/ru/post/1239902/


All Articles