NumPy - Reverse Array


NumPy - Reverse Array

In Python, we can reverse a 1D numpy array, or reverse the rows or columns of a 2D array, using slicing technique.

In this tutorial, you will learn how to reverse a numpy array using slicing technique in Python, with examples.

Syntax

The syntax to reverse a 1D array is as shown in the following.

arr[::-1]

The syntax to reverse a 2D array along axis=0 is as shown in the following.

arr[::-1, :]

The syntax to reverse a 2D array along axis=1 is as shown in the following.

arr[:, ::-1]

where

ParameterDescription
arrThe NumPy array you want to reverse.

Examples

Let's explore examples of reversing arrays using NumPy.

1. Reverse 1D Array

In this example, we take a 1D NumPy array, and reverse the items in this array. We shall print the reversed array to the standard output.

Python Program

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
reversed_arr = arr[::-1]

print(reversed_arr)

Output

[5 4 3 2 1]

2. Reverse the order of items in 2D Array along axis=0

In this example, we take a 2D NumPy array, and reverse the order of items along axis=0 in this array.

Python Program

import numpy as np

arr = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])

reversed_rows_arr = arr[::-1, :]

print(reversed_rows_arr)

Output

[[7 8 9]
 [4 5 6]
 [1 2 3]]

3. Reverse the order of items in 2D Array along axis=1

In this example, we take a 2D NumPy array, and reverse the order of items along axis=1 in this array.

Python Program

import numpy as np

arr = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])

reversed_arr = arr[:, ::-1]

print(reversed_arr)

Output

[[3 2 1]
 [6 5 4]
 [9 8 7]]

Reversing higher dimensional arrays

Similar to the syntax specified or what is given in the examples, we can reverse higher dimensional numpy arrays as well.

For example, the syntax to reverse a 3D array along axis=0 is

arr[::-1, :, :]

The syntax to reverse a 4D array along axis=2 is

arr[:, :, ::-1, :]

Summary

In this NumPy Tutorial, we have seen how to reverse a numpy array using slicing technique in Python, with examples. The example include reversing a 1D array, reversing a 2D array along axis=0 or axis=1.