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

import numpy as np

arr = np.array([5, 2, 9, 1, 7])

result = np.sort(arr)
print(result)

Output:

[1 2 5 7 9]

βœ… 2. Sorting Strings

arr = np.array(["banana", "apple", "cherry"])

print(np.sort(arr))

Output:

['apple' 'banana' 'cherry']

πŸ§ͺ 3. Sorting Boolean Arrays

arr = np.array([True, False, True])

print(np.sort(arr))

Output:

[False True True]

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


🧱 4. Sorting a 2D Array

πŸ”Ή Sort Row-wise (axis=1)

arr = np.array([[5, 3, 8], [2, 9, 1]])

print(np.sort(arr, axis=1))

Output:

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

πŸ”Ή Sort Column-wise (axis=0)

print(np.sort(arr, 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.

arr = np.array([30, 10, 50, 20])

idx = np.argsort(arr)
print(idx)

Output:

[1 3 0 2]

Now you can reorder:

print(arr[idx])

πŸ”„ 6. Sort in Descending Order

NumPy doesn’t have built-in descending sort, but we can reverse:

arr = np.array([10, 5, 50, 20])

print(np.sort(arr)[::-1])


πŸ“Œ 7. Sorting Structured Arrays

Useful for sorting data by field (like database sorting).

data = np.array(
[(25, 'Alice'), (30, 'Bob'), (22, 'John')],
dtype=[('age', int), ('name', 'U10')]
)

print(np.sort(data, order='age'))


🧠 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:

arr = np.array([[7,2,3], [9,1,5], [4,6,8]])

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

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *