NumPy Sorting Arrays
🧹 NumPy Sorting Arrays
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:
