Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 09

Sorting and Comparing

Sort 1-D and 2-D arrays with np.sort and an axis, sort in place, find the sort order with argsort, and compare arrays element by element.

Intermediate25 min
Sorting and Comparing hero Module 23 Lesson 9

np.sort returns a sorted copy. Numbers sort by value, text sorts alphabetically, and False comes before True. On a 2-D array, the axis argument decides which way to sort.

A 3 by 3 array before and after sorting each column

Sort a 1-D array

There is no reverse argument. For largest first, sort and then reverse with [::-1].

python
import numpy as np

a = np.array([110, 20, -30, 40, 50, 160, 7, 8, 90])
print(np.sort(a))
print(np.sort(a)[::-1])
print(np.sort(np.array(["pear", "fig", "apple"])))
print(np.sort(np.array([True, False, True])))

Output:

text
[-30   7   8  20  40  50  90 110 160]
[160 110  90  50  40  20   8   7 -30]
['apple' 'fig' 'pear']
[False  True  True]

Sort a 2-D array by axis

By default each row is sorted on its own. axis=0 sorts down each column. axis=None flattens the array and sorts everything into one line.

python
import numpy as np

m = np.array([[110, 20, -30], [40, 50, 160], [7, 8, 90]])
print(np.sort(m))
print(np.sort(m, axis=0))
print(np.sort(m, axis=None))

Output:

text
[[-30  20 110]
 [ 40  50 160]
 [  7   8  90]]
[[  7   8 -30]
 [ 40  20  90]
 [110  50 160]]
[-30   7   8  20  40  50  90 110 160]

Sort in place, or get the order

a.sort() sorts the array itself and returns None. np.argsort returns the positions that would sort the array, which is useful when another array must follow the same order.

python
import numpy as np

times = np.array([42, 17, 30])
names = np.array(["red team", "blue team", "green team"])

order = np.argsort(times)
print(order)
print(names[order])

times.sort()
print(times)

Output:

text
[1 2 0]
['blue team' 'green team' 'red team']
[17 30 42]

Compare arrays

>, <, ==, !=, >=, and <= compare element by element and return an array of True and False. Each has a function form, such as np.greater or np.not_equal. np.array_equal asks whether two whole arrays match.

python
import numpy as np

a = np.array([1, 8, 3, 6])
b = np.array([3, 8, 5, 2])
print(a > b)
print(np.greater(a, b))
print(np.equal(a, b))
print(a <= b)
print(np.array_equal(a, a.copy()))

Output:

text
[False False False  True]
[False False False  True]
[False  True False False]
[ True  True  True False]
True

Key takeaways

  • np.sort returns a copy. a.sort() changes a and returns None

  • 2-D sorts each row by default. axis=0 sorts each column

  • argsort gives the positions in sorted order

  • Comparisons return a True/False array of the same shape

  • Next: Filtering Arrays

  • Previous: Copy and View

Loading playground…

Check your understanding

Sorting and Comparing Quiz

What does np.sort(np.array([3, 2, 0, 1])) give?

1 / 10