Reverse NumPy Array: Quick Guide & Examples
You can use the numpy function np.flip() to reverse the order of an array. The syntax of the function is as follows:
np.flip(array, axis=None)
The parameter “array” is the array that needs to be sorted in reverse order, and the parameter “axis” indicates which axis to sort along. By default, it is set to None, which means the entire array will be sorted in reverse order.
Here is an example of reversing order using the np.flip() function:
import numpy as np
# 创建一个一维数组
arr = np.array([1, 2, 3, 4, 5])
# 对数组进行倒序排列
arr_reverse = np.flip(arr)
print(arr_reverse)
# 输出:[5 4 3 2 1]
import numpy as np
# 创建一个二维数组
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 对数组进行倒序排列
arr_reverse = np.flip(arr, axis=0)
print(arr_reverse)
# 输出:
# [[7 8 9]
# [4 5 6]
# [1 2 3]]
By using the np.flip() function, it is easy to reverse the order of a numpy array.