w3resource

NumPy: Move the specified axis backwards, until it lies in a given position

NumPy: Array Object Exercise-53 with Solution

Write a NumPy program to move the specified axis backwards, until it lies in a given position.
Move the following 3rd array axes to first position.
(2,3,4,5)

Pictorial Presentation:

Python NumPy: Move axes of an array to new positions

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a NumPy array filled with ones of shape (2, 3, 4, 5)
x = np.ones((2, 3, 4, 5))

# Using rollaxis to roll the axis at index 3 (last axis) to index 1
# Printing the shape of the array after rolling the axis from index 3 to index 1
print(np.rollaxis(x, 3, 1).shape) 

Sample Output:

(2, 5, 3, 4)

Explanation:

In the above code -

x = np.ones((2, 3, 4, 5)): This part creates a 4D array x with the given shape (2, 3, 4, 5), filled with ones.

print(np.rollaxis(x, 3, 1).shape): The np.rollaxis() function takes three arguments: the input array, the axis to be rolled, and the axis to be rolled to. In this case, it rolls axis 3 (the fourth axis) to the position of axis 1 (the second axis). As a result, the shape of the new array is (2, 5, 3, 4).

Python-Numpy Code Editor:

Previous: Write a NumPy program to move axes of an array to new positions. Other axes remain in their original order.
Next: Write a NumPy program to convert specified inputs to arrays with at least one dimension.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-53.php