Rob*_*eph 4 python numpy vectorization
我正处于学习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.
Run Code Online (Sandbox Code Playgroud)
注意:我意识到我可以执行以下操作,但我想了解矢量化选项.
t = np.array([ np.rot90(x, k=-1) for x in a])
Run Code Online (Sandbox Code Playgroud)
无需单独进行旋转: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)) # leftRun Code Online (Sandbox Code Playgroud)
这将旋转所有矩阵,如:
>>> 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]]])
Run Code Online (Sandbox Code Playgroud)
或者如果你想向左旋转:
>>> 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]]])
Run Code Online (Sandbox Code Playgroud)
请注意,您只能指定axesfrom numpy 1.12和(可能)将来的版本.
| 归档时间: |
|
| 查看次数: |
1070 次 |
| 最近记录: |