
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Move Axes of a NumPy Array to New Positions
To move axes of an array to new positions, use the numpy.moveaxis() method in Python Numpy. Here, the 1st parameter is the array whose axes should be reordered. The 2nd parameter is the source int or sequence of int i.e. original positions of the axes to move. These must be unique. The 3rd parameter is the destination int or sequence of int. The Destination positions for each of the original axes. These must also be unique.
Steps
At first, import the required library −
import numpy as np
Create an array with zeros −
arr = np.zeros((2, 3, 4))
Displaying our array −
print("Array...
",arr)
Get the datatype −
print("
Array datatype...
",arr.dtype)
Get the dimensions of the Array −
print("
Array Dimensions...
",arr.ndim)
Get the shape of the Array −
print("
Our Array Shape...
",arr.shape)
To move axes of an array to new positions, use the numpy.moveaxis() method −
print("
Result
",np.moveaxis(arr, 0, -1).shape) print("
Result
",np.moveaxis(arr, -1, 0).shape)
Example
import numpy as np # Create an array with zeros arr = np.zeros((2, 3, 4)) # Displaying our array print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # To move axes of an array to new positions, use the numpy.moveaxis() method in Python Numpy # Here, the 1st parameter is the array whose axes should be reordered. # The 2nd parameter is the sourceint or sequence of int i.e. original positions of the axes to move. These must be unique. # The 3rd parameter is the destinationint or sequence of int. The Destination positions for each of the original axes. # These must also be unique. print("
Result
",np.moveaxis(arr, 0, -1).shape) print("
Result
",np.moveaxis(arr, -1, 0).shape) print("
Result
",np.transpose(arr).shape) print("
Result
",np.swapaxes(arr, 0, -1).shape)
Output
Array... [[[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]] Array datatype... float64 Array Dimensions... 3 Our Array Shape... (2, 3, 4) Result (3, 4, 2) Result (4, 2, 3) Result (4, 3, 2) Result (4, 3, 2)
Advertisements