You can reverse a NumPy array using the [::-1] slicing syntax. This creates a new reversed array, leaving the original array unchanged.
Here’s an example of how to reverse a 1-D NumPy array:
How to reverse a vector
import numpy as np a = np.array([1, 2, 3, 4, 5]) result = a[::-1] print(result) # Output: [5 4 3 2 1]
How to reverse a multi-dimensional array
If you want to reverse a multi-dimensional array, you can reverse each axis separately using slicing. For example, to reverse a 2-D array along the second axis (columns), you can do the following:
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) result = a[:, ::-1] print(result) # Output: # [[3 2 1] # [6 5 4] # [9 8 7]]
Note that the [::-1] slicing syntax works for any array shape and any number of dimensions, so you can use it to reverse arrays of any size and shape.