Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Reason why numpy rollaxis is so confusing?

The behavior of the numpy rollaxis function confuses me. The documentation says:

Roll the specified axis backwards, until it lies in a given position.

And for the start parameter:

The axis is rolled until it lies before this position.

To me, this is already somehow inconsistent.

Ok, straight forward example (from the documentation):

>>> a = np.ones((3,4,5,6))
>>> np.rollaxis(a, 1, 4).shape
(3, 5, 6, 4)

The axis at index 1 (4) is rolled backward till it lies before index 4.

Now, when the start index is smaller than the axis index, we have this behavior:

>>> np.rollaxis(a, 3, 1).shape
(3, 6, 4, 5)

Instead of shifting the axis at index 3 before index 1, it ends up at 1.

Why is that? Why isn't the axis always rolled to the given start index?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

NumPy v1.11 and newer includes a new function, moveaxis, that I recommend using instead of rollaxis (disclaimer: I wrote it!). The source axis always ends up at the destination, without any funny off-by-one issues depending on whether start is greater or less than end:

import numpy as np

x = np.zeros((1, 2, 3, 4, 5))
for i in range(5):
    print(np.moveaxis(x, 3, i).shape)

Results in:

(4, 1, 2, 3, 5)
(1, 4, 2, 3, 5)
(1, 2, 4, 3, 5)
(1, 2, 3, 4, 5)
(1, 2, 3, 5, 4)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...