numpy rollaxis - how exactly does it work?

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


np.rollaxis(tensor,axis,start) moves the axis specified by the axis parameter to the position before the axis that is located at start with no exceptions.

Say the axes are (1, 2, 3, 4, 5, 6) if axis points to the 3, and start points to the 5, then after the roll, the 3 will be just before the 5. Since the 3 in my example is at position 2 of the dimensions tuple, axis=2. Also, since the 5 is at position 4, start=4.

Like this:

>>> a.shape

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

>>> np.rollaxis(a, 2, 4).shape

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

As you can see, the 3 is now right before the 5. NOTE: The 3 does not move to position 4, but rather to the position before the value originally at position 4 (which in this case turns out to be position 3).

Negative numbers specify positions just like they do for lists. In other words, axis=-1 specifies the last position. In my example above there is a 6 in the -1 position and a 5 in the -2 position. Both axis and start may be negative.

You can do the same thing I did above with negative numbers like this:

>>> a.shape

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

>>> np.rollaxis(a, -4, -2).shape

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

If start is not specified, it defaults to 0 which is the first position. That means that if start is not specified, the specified axis will always be moved to the beginning, which is before the 1 which was originally at position 0.

If this is confusing there is another explanation that might make more sense here: Reason why numpy rollaxis is so confusing?

Tags:

Python

Numpy