English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Sorting is the process of arranging elements in an ordered sequence.
An ordered sequence is any sequence that has an order corresponding to its elements, such as numbers or letters, in ascending or descending order.
NumPy ndarray objects have a named sort() a function that sorts the specified array.
Sort the array:
import numpy as np arr = np.array([3, 2, 0, 1]) print(np.sort(arr))
Running Result:
[0 1 2 3]
You can also sort string arrays or any other data type:
Sort arrays in alphabetical order:
import numpy as np arr = np.array(['banana', 'cherry', 'apple']) print(np.sort(arr))
Running Result:
['apple' 'banana' 'cherry']
Sort boolean arrays:
import numpy as np arr = np.array([True, False, True]) print(np.sort(arr))
Running Result:
[False True True]
If the sort() method is used on a two-dimensional array, the two arrays will be sorted:
For 2-D Array Sorting
import numpy as np arr = np.array([3, 2, 4], [5, 0, 1]] print(np.sort(arr))
Running Result:
[[2 3 4] [0 1 5]]