Sorting NumPy arrays can be done using the numpy.sort() function or the array.sort() method.
import numpy as np
arr = np.array([3, 1, 2, 5, 4])
# Sort the array
sorted_arr = np.sort(arr)
print(sorted_arr)
[1 2 3 4 5]
import numpy as np
arr = np.array([3, 1, 2, 5, 4])
# Sort the array in-place
arr.sort()
print(arr)
[1 2 3 4 5]
You can also specify the axis parameter to sort along a specific axis for multi-dimensional arrays. By default, the axis parameter is None, which means the array is flattened before sorting.
import numpy as np
arr = np.array([[3, 1, 2], [5, 4, 6]])
# Sort along the first axis (rows)
sorted_arr_axis0 = np.sort(arr, axis=0)
# Sort along the second axis (columns)
sorted_arr_axis1 = np.sort(arr, axis=1)
print("Sorted along axis 0:")
print(sorted_arr_axis0)
print("\nSorted along axis 1:")
print(sorted_arr_axis1)
Sorted along axis 0:
[[3 1 2]
[5 4 6]]
Sorted along axis 1:
[[1 2 3]
[4 5 6]]
These are the basic ways to sort NumPy arrays. Depending on your needs, you can choose between sorting the array in-place or creating a sorted copy using the appropriate method.