numpy rollaxis-它是如何工作的? [英] numpy rollaxis - how exactly does it work?
问题描述
因此,我正在尝试numpy,并且在rollaxis方法中遇到了一个奇怪的(?)行为.
So I was experimenting with numpy and I ran across a strange (?) behavior in the rollaxis method.
In [81]: a = np.ones((4, 3, 2))
In [82]: a.shape
Out[82]: (4, 3, 2)
In [83]: x = np.rollaxis(a, 2)
In [84]: x.shape
Out[84]: (2, 4, 3)
In [85]: np.rollaxis(x, -2).shape
Out[85]: (4, 2, 3)
-2是否不能反转横滚轴?我想做的是应用一个仅在第2个坐标为第一个坐标时才能应用的矩阵.但是然后我想将数组放回其原始形式.我发现唯一起作用的是两次应用np.rollaxis(x, 2)
或应用np.rollaxis(x, 0, start=3)
.我只是通过猜测发现它们,我不知道它们为什么起作用.他们似乎也掩盖了我真正想做的事情.有人可以解释一下我应该反向"滚动的方式,或者我做错了什么吗?
Shouldn't the -2 reverse the rollaxis? What I'm trying to do is apply a matrix that can only be applied when the 2 coordinate is first. But then I want to put my array back into its original form. The only things which I have found to work are applying np.rollaxis(x, 2)
twice, or applying np.rollaxis(x, 0, start=3)
. I just found these by guessing and I have no idea why they work. They also seem to be obscuring what I'm really trying to do. Could somebody please explain the way that I should 'reverse' a roll, or what I'm doing wrong?
(是否有Python方式来做到这一点?)
(Is there a pythonic way to do this?)
推荐答案
方法rollaxis
def rollaxis(a, axis, start=0):
将选择的axis
重新分配到start
位置"
reallocates the chosen axis
at the start
"position"
按照您的示例:
a = np.ones((4, 3, 2))
x = np.rollaxis(a, 2)
# x.shape = (2, 4, 3)
关于形状:rollaxis
会将最后一个axis=2
中的数字2
带到自start=0
开始的第一个位置.
Concerning shapes: rollaxis
will bring the number 2
, which is in your last axis=2
, to the the first position, since start=0
.
通过使用
x2 = np.rollaxis(x, -2)
# x2.shape = (4,2,3)
rollaxis
将带数字4,这是倒数第二个轴,axis=-2
,并从start=0
开始在第一个位置重新分配.这就解释了您的结果(4,2,3)
,而不是(4,3,2)
.
rollaxis
will bring the number 4, which is the second last axis, axis=-2
, and reallocate at the first position, since start=0
. That explains your result (4,2,3)
, instead of (4,3,2)
.
按照相同的逻辑,这解释了为什么两次应用rollaxis(a,2)
会将数组形状恢复为初始形状. np.rollaxis(x, 0, start=3)
也起作用,因为第一个轴转到最后一个轴,换句话说(2,4,3)中的数字2到达最后一个结果(4,3,2).
Following the same logic, this explains why applying rollaxis(a,2)
twice brings the array shape back to the initial one. np.rollaxis(x, 0, start=3)
also works because the first axis goes to the last one, in other words the number 2 in (2,4,3) goes to the last position resulting (4,3,2).
这篇关于numpy rollaxis-它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!