# Roll the specified axis backwards until it lies in a given position in Numpy

NumpyServer Side ProgrammingProgramming

To roll the specified axis backwards, until it lies in a given position, use the numpy.moveaxis() method in Python Numpy. Here,

• The 1st parameter is the Input array
• The 2nd parameter is the axis to be rolled. The positions of the other axes do not change relative to one another.
• The 3rd parameter is the start i.e. when start <= axis, the axis is rolled back until it lies in this position.

When start > axis, the axis is rolled until it lies before this position.

## Steps

At first, import the required library −

import numpy as np

Create an array with ones −

arr = np.ones((2, 3, 4, 5))

Displaying our array −

print("Array...\n",arr)

Get the datatype −

print("\nArray datatype...\n",arr.dtype)


Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

To roll the specified axis backwards, until it lies in a given position, use the numpy.moveaxis() method −

print("\nResult\n",np.rollaxis(arr, 3, 1).shape)
print("\nResult\n",np.rollaxis(arr, 2).shape)
print("\nResult\n",np.rollaxis(arr, 1).shape)
print("\nResult\n",np.rollaxis(arr, 1, 4).shape)

## Example

import numpy as np

# Create an array with ones
arr = np.ones((2, 3, 4, 5))

# Displaying our array
print("Array...\n",arr)

# Get the datatype
print("\nArray datatype...\n",arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# To roll the specified axis backwards, until it lies in a given position, use the numpy.moveaxis() method in Python Numpy
# Here, the 1st parameter is the Input array
# The 2nd parameter is the axis to be rolled. The positions of the other axes do not change relative to one another.
# The 3rd parameter is the start i.e. when start <= axis, the axis is rolled back until it lies in this position.
# When start > axis, the axis is rolled until it lies before this position.
print("\nResult\n",np.rollaxis(arr, 3, 1).shape)

print("\nResult\n",np.rollaxis(arr, 2).shape)

print("\nResult\n",np.rollaxis(arr, 1).shape)

print("\nResult\n",np.rollaxis(arr, 1, 4).shape)

## Output

Array...
[[[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]

[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]

[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]]

[[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]

[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]

[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]]]

Array datatype...
float64

Array Dimensions...
4

Our Array Shape...
(2, 3, 4, 5)

Result
(2, 5, 3, 4)

Result
(4, 2, 3, 5)

Result
(3, 2, 4, 5)

Result
(2, 4, 5, 3)
Updated on 17-Feb-2022 10:06:02