使用numpy.vectorize()旋转NumPy数组的所有元素 [英] Using numpy.vectorize() to rotate all elements of a NumPy array

查看:175
本文介绍了使用numpy.vectorize()旋转NumPy数组的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正处于学习NumPy的初期阶段.我有一个3x3矩阵的Numpy数组.我想创建一个新数组,其中每个矩阵都旋转90度.我已经研究了答案但我仍然不知道自己在做什么错.

I am in the beginning phases of learning NumPy. I have a Numpy array of 3x3 matrices. I would like to create a new array where each of those matrices is rotated 90 degrees. I've studied this answer but I still can't figure out what I am doing wrong.

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.

注意:我意识到我可以执行以下操作,但我想了解向量化选项.

Note: I realize I could do the following but I'd like to understand the vectorized option.

t = np.array([ np.rot90(x, k=-1) for x in a])

推荐答案

无需单独进行轮换:numpy具有内置的

No need to do the rotations individually: numpy has a builtin numpy.rot90(m, k=1, axes=(0, 1)) function. By default the matrix is thus rotate over the first and second dimension.

如果要深一层旋转,只需设置发生旋转的轴,深一层即可(如果要沿不同方向旋转,可以选择交换它们).或根据文档指定:

If you want to rotate one level deeper, you simply have to set the axes over which rotation happens, one level deeper (and optionally swap them if you want to rotate in a different direction). Or as the documentation specifies:

axes: (2,) array_like

   阵列在由 轴.轴必须不同.

   The array is rotated in the plane defined by the axes. Axes must be different.

因此,我们在 y z 平面上旋转(如果我们标注尺寸 x y z ),因此我们指定(2,1)(1,2).

So we rotate over the y and z plane (if we label the dimensions x, y and z) and thus we either specify (2,1) or (1,2).

当您要旋转到右/左时,您要做的就是正确设置axes:

All you have to do is set the axes correctly, when you want to rotate to the right/left:

np.rot90(a,axes=(2,1)) # right
np.rot90(a,axes=(1,2)) # left

这将旋转所有矩阵,例如:

This will rotate all matrices, like:

>>> 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]]])

请注意,您只能从 numpy 1.12和(可能)将来的版本中指定axes.

Note that you can only specify the axes from numpy 1.12 and (probably) future versions.

这篇关于使用numpy.vectorize()旋转NumPy数组的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆