更新时间:2023-11-10 10:03:16
在您使用k=3
的情况下,np.rot90
的代码可以做到:
The code for np.rot90
does, in your case of k=3
:
# k == 3
return fliplr(m.swapaxes(0, 1))
所以
In [789]: np.fliplr(ar.swapaxes(0, 1))
Out[789]:
array([[-11, 0],
...
[ -3, 8],
[ -2, 9]])
所以你的
fliplr(rot90(ar, 3))
成为
np.fliplf(np.fliplr(ar.swapaxes(0, 1)))
# the flips cancel
ar.swapaxes(0,1)
# but this is just
ar.T
因此,您的一对动作会减少以进行转置.
So your pair of actions reduce to transpose.
transpose
(和swap
)仅更改数组的.shape
和strides
属性;这是一个视图,而不是副本.
transpose
(and the swap
) just changes the .shape
and strides
attributes of the array; it is a view, not a copy.
np.fliplr
还会创建一个视图,并随[:,::-1]
改变步幅.
np.fliplr
also creates a view, changing strides with the [:,::-1]
.
原始的ar
:
In [818]: ar
Out[818]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[-11, -10, -9, -8, -7, -6, -5, -4, -3, -2]])
In [819]: x=np.fliplr(np.rot90(ar,3)) # your pair of actions
In [820]: x
Out[820]:
array([[ 0, -11],
[ 1, -10],
...
[ 8, -3],
[ 9, -2]])
In [821]: x[0,1]=11
In [822]: x
Out[822]:
array([[ 0, 11],
[ 1, -10],
...
[ 9, -2]])
In [823]: ar
Out[823]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[ 11, -10, -9, -8, -7, -6, -5, -4, -3, -2]])
更改x
的值将更改ar
的值.尽管使用了2个功能,x
仍然是ar
的view
.
Changing a value of x
changes a value of ar
. Despite the use of 2 functions, x
is still a view
of ar
.
这两个函数不是必需的,但它们也不是那么昂贵.我们所说的是微秒v纳秒的时间. (我在Ipython中的timeit
时间要小得多)
The 2 functions aren't needed, but they aren't that expensive either. We are talking microseconds v nanoseconds of time. (my timeit
times in Ipython are much smaller yours)
In [824]: timeit np.fliplr(np.rot90(ar,3))
100000 loops, best of 3: 8.28 µs per loop
In [825]: timeit ar.T
1000000 loops, best of 3: 455 ns per loop