Home »
Python »
Python Programs
Flip a NumPy array along with a specified axis without changing its shape
By IncludeHelp Last updated : November 25, 2023
Problem statement
Given a NumPy array, write a Python program to flip it along with an axis without changing its shape i.e., if the input array has shape (n, m), then the resulting array should also have shape (n, m).
Input:
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
axis = 0
Output:
[[7, 8, 9], [4, 5, 6], [1, 2, 3]]
Solution Approach: Use the numpy.flip() method
To flip a NumPy array along with the axis without changing its shape, use the numpy.flip() method by passing the array and axis. This method reverses the order of elements in an array along the given axis.
Syntax
Below is the syntax of the numpy.flip() method:
numpy.flip(arr, axis=None)
Example
In this example, we have a NumPy array arr and flipping its elements with axis 1.
# Importing numpy library
import numpy as np
# Creating an array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Printing original array
print("Original array\n", arr, "\n")
# Defining an axis
axis = 1
# Flipping array
result = np.flip(arr, axis)
# Display result
print("Result:\n", result)
Output
The output of the above example is:
Original array
[[1 2 3]
[4 5 6]
[7 8 9]]
Result:
[[3 2 1]
[6 5 4]
[9 8 7]]
In the above example, we flipped elements along with axis 1, now change is with axis 0.
# Defining an axis
axis = 0
# Flipping array
result = np.flip(arr, axis)
Then the output will be:
Original array
[[1 2 3]
[4 5 6]
[7 8 9]]
Result:
[[7 8 9]
[4 5 6]
[1 2 3]]
Python NumPy Programs »