在最后2个维度中旋转5D阵列

Bab*_*bak 5 python arrays numpy rotation vectorization

我有一个5D数组'a',大小(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]])
Run Code Online (Sandbox Code Playgroud)

我想要做的是将这个5D阵列旋转180度,但仅在最后两个维度中,不改变它们的位置.所以输出[0,0,0]应如下所示:

out[0,0,0]:
array([[3, 2],
       [1, 0]])
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

out = np.rot90(a, 2)
out[0,0,0]:
array([[40, 41],
       [42, 43]])
Run Code Online (Sandbox Code Playgroud)

rot90功能显然可以旋转整个阵列.

注意:如果可能,我想避免使用for循环

Ale*_*ley 2

要将最后两个轴旋转 180 度,请传递axes=(-2, -1)np.rot90

>>> a180 = np.rot90(a, 2, axes=(-2, -1))
>>> a180[0, 0, 0]
array([[3, 2],
       [1, 0]])
Run Code Online (Sandbox Code Playgroud)

如果您的 NumPy 版本没有 参数axesnp.rot90还有其他选择。

一种方法是使用索引:

a180 = a[..., ::-1, ::-1]
Run Code Online (Sandbox Code Playgroud)

rot90翻转数组的两个轴,因此要使用它,您需要转置(反转轴)、旋转,然后再次转回。例如:

np.rot90(a.T, 2).T
Run Code Online (Sandbox Code Playgroud)