Error when using rot90 on 3D numpy array with 3 arguments

牧云@^-^@ 提交于 2020-07-07 19:28:11

问题


Python 2.7.10; Numpy 1.8.1

While going through the examples on matrix rotation here I keep getting an error.

The code:

m = np.arange(8).reshape((2,2,2))
np.rot90(m, 1, (1,2))

The error:

TypeError: rot90() takes at most 2 arguments (3 given)

I tried copy and pasting, and typing out, the code, but no joy.

I understand the text of the error, but not the why, especially since it is code direct from the SciPy site.

What is the issue?


回答1:


Unfortunately, I think the New in version 1.12.0. has been put at the wrong place. In fact when you look at the 1.8.1 documentation you'll see that it only takes the arguments m and k:

numpy.rot90(m, k=1)

It was added in version 1.12.0 and now rot90 accepts the axis argument:

numpy.rot90(m, k=1, axes=(0, 1)

The corresponding changelog is here.

axes keyword argument for rot90

The axes keyword argument in rot90 determines the plane in which the array is rotated. It defaults to axes=(0,1) as in the original function.

But the function itself isn't very long, you probably can just copy it over:

def rot90(m, k=1, axes=(0,1)):
    axes = tuple(axes)
    if len(axes) != 2:
        raise ValueError("len(axes) must be 2.")

    m = asanyarray(m)

    if axes[0] == axes[1] or absolute(axes[0] - axes[1]) == m.ndim:
        raise ValueError("Axes must be different.")

    if (axes[0] >= m.ndim or axes[0] < -m.ndim
        or axes[1] >= m.ndim or axes[1] < -m.ndim):
        raise ValueError("Axes={} out of range for array of ndim={}."
            .format(axes, m.ndim))

    k %= 4

    if k == 0:
        return m[:]
    if k == 2:
        return flip(flip(m, axes[0]), axes[1])

    axes_list = arange(0, m.ndim)
    (axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]],
                                                axes_list[axes[0]])

    if k == 1:
        return transpose(flip(m,axes[1]), axes_list)
    else:
        # k == 3
        return flip(transpose(m, axes_list), axes[1])

def flip(m, axis):
    if not hasattr(m, 'ndim'):
        m = asarray(m)
    indexer = [slice(None)] * m.ndim
    try:
        indexer[axis] = slice(None, None, -1)
    except IndexError:
        raise ValueError("axis=%i is invalid for the %i-dimensional input array"
                         % (axis, m.ndim))
    return m[tuple(indexer)]


来源:https://stackoverflow.com/questions/45870603/error-when-using-rot90-on-3d-numpy-array-with-3-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!