使用numpy.vectorize()旋转NumPy数组的所有元素
问题内容:
我正处于学习NumPy的初期阶段。我有一个3x3矩阵的Numpy数组。我想创建一个新数组,其中每个矩阵都旋转90度。我已经研究了这个答案,但仍然无法弄清楚自己在做什么错。
import numpy as np
# 3x3
m = np.array([[1,2,3], [4,5,6], [7,8,9]])
# array of 3x3
a = np.array([m,m,m,m])
# rotate a single matrix counter-clockwise
def rotate90(x):
return np.rot90(x)
# function that can be called on all elements of an np.array
# Note: I've tried different values for otypes= without success
f = np.vectorize(rotate90)
result = f(a)
# ValueError: Axes=(0, 1) out of range for array of ndim=0.
# The error occurs in NumPy's rot90() function.
注意:我知道我可以执行以下操作,但是我想了解向量化选项。
t = np.array([ np.rot90(x, k=-1) for x in a])
问题答案:
无需单独进行旋转:numpy
具有内置 numpy.rot90(m, k=1, axes=(0, 1))
功能。因此,默认情况下,矩阵在第一维和第二维上旋转。
如果要深一层旋转,只需设置发生旋转的轴,深一层即可(如果要沿不同方向旋转,可以选择交换它们)。或根据文档指定:
axes: (2,) array_like
阵列在轴定义的平面中旋转。轴必须不同。
因此,我们在 y 和 z 平面上旋转(如果我们标注尺寸 x , y 和 z ),因此我们指定(2,1)
或(1,2)
。
axes
当您想 左右 旋转时,您所要做的就是正确设置:
np.rot90(a **,axes=(2,1)** ) # right
np.rot90(a **,axes=(1,2)** ) # left
这将旋转所有矩阵,例如:
>>> np.rot90(a,axes=(2,1))
array([[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]],
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]],
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]],
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]])
或者,如果您想 向左旋转 :
>>> np.rot90(a,axes=(1,2))
array([[[3, 6, 9],
[2, 5, 8],
[1, 4, 7]],
[[3, 6, 9],
[2, 5, 8],
[1, 4, 7]],
[[3, 6, 9],
[2, 5, 8],
[1, 4, 7]],
[[3, 6, 9],
[2, 5, 8],
[1, 4, 7]]])
请注意,您只能指定axes
从 numpy的1.12和(可能)未来的版本 。