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?
rollaxis() function roll the specified axis backwards, until it lies in a given position. Syntax : numpy.rollaxis(arr, axis, start=0) Parameters : arr : [ndarray] Input array. axis : [int] The axis to roll backwards.
Axes are defined for arrays with more than one dimension. A 2-dimensional array has two corresponding axes: the first running vertically downwards across rows (axis 0), and the second running horizontally across columns (axis 1). Many operation can take place along one of these axes.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With