NumPy Sorting Arrays
π§Ή NumPy Sorting Arrays (Complete Guide)
Sorting helps rearrange array elements in ascending order (default) or descending using additional logic.
NumPy provides:
β np.sort()
β np.argsort()
β Sorting by axis
β Structured array sorting
β 1. Sorting a 1D Array
Output:
β 2. Sorting Strings
Output:
π§ͺ 3. Sorting Boolean Arrays
Output:
(Booleans sort as False=0, True=1)
π§± 4. Sorting a 2D Array
πΉ Sort Row-wise (axis=1)
Output:
πΉ Sort Column-wise (axis=0)
Output:
π 5. argsort() β Get Sorted Indexes
It returns the indices that would sort the array, instead of the sorted values.
Output:
Now you can reorder:
π 6. Sort in Descending Order
NumPy doesnβt have built-in descending sort, but we can reverse:
π 7. Sorting Structured Arrays
Useful for sorting data by field (like database sorting).
π§ Summary Table
| Method | Purpose |
|---|---|
np.sort() |
Sort array (returns new sorted array) |
np.argsort() |
Return index positions for sorted order |
sorted_arr[::-1] |
Descending sort |
axis parameter |
Sort rows or columns in 2D |
order parameter |
Sort structured arrays |
π― Practice Challenge
Try this:
