Sorting involves organizing elements in a specific order, such as numeric or alphabetical, either in ascending or descending sequence. The NumPy ndarray object provides a function called sort()
that can sort a specified array.
Arrange the array in order:
import numpy as np arr = np.array([3, 2, 0, 1]) print(np.sort(arr)) |
Note: This method returns a copy of the array without modifying the original array. |
You can also sort arrays containing strings or any other data type.
Arrange the array in alphabetical order:
import numpy as np arr = np.array([‘banana’, ‘cherry’, ‘apple’]) print(np.sort(arr)) |
Arrange a boolean array:
import numpy as np arr = np.array([True, False, True]) print(np.sort(arr)) |
If you apply the sort() method to a 2-D array, both dimensions will be sorted.
Arrange a 2-D array in order:
import numpy as np arr = np.array([[3, 2, 4], [5, 0, 1]]) print(np.sort(arr)) |