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:

[1 2 5 7 9]

 2. Sorting Strings


 

Output:

['apple' 'banana' 'cherry']

🧪 3. Sorting Boolean Arrays


 

Output:

[False True True]

(Booleans sort as False=0, True=1)


🧱 4. Sorting a 2D Array

 Sort Row-wise (axis=1)


 

Output:

[[3 5 8]
[1 2 9]]

 Sort Column-wise (axis=0)

Output:

[[2 3 1]
[5 9 8]]


🚀 5. argsort() — Get Sorted Indexes

It returns the indices that would sort the array, instead of the sorted values.


 

Output:

[1 3 0 2]

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

MethodPurpose
np.sort()Sort array (returns new sorted array)
np.argsort()Return index positions for sorted order
sorted_arr[::-1]Descending sort
axis parameterSort rows or columns in 2D
order parameterSort structured arrays

🎯 Practice Challenge

Try this:


 

1. Sort row-wise
2. Sort column-wise
3. Get sorted index of first row
4. Print array sorted in descending order

You may also like...