Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

python - numpy rollaxis - how exactly does it work?

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)

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?

(Is there a pythonic way to do this?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The method rollaxis

def rollaxis(a, axis, start=0):

reallocates the chosen axis at the start "position"

Following your example:

a = np.ones((4, 3, 2))
x = np.rollaxis(a, 2)
# x.shape = (2, 4, 3)

Concerning shapes: rollaxis will bring the number 2, which is in your last axis=2, to the the first position, since start=0.

By using

x2 = np.rollaxis(x, -2)
# x2.shape = (4,2,3)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...