Last updated

Sorting Arrays

Definition: np.sort returns a new, sorted copy of an array. The original is left unchanged.

Example 1 — sort numbers

import numpy as np
a = np.array([3, 1, 4, 1, 5, 9, 2])
print(np.sort(a))   # [1 1 2 3 4 5 9]
print(a)            # original unchanged

Example 2 — sort text

import numpy as np
names = np.array(["Sam", "Alex", "Jo"])
print(np.sort(names))   # alphabetical

Example 3 — sorting a 2D array

By default each row is sorted independently:

import numpy as np
b = np.array([[3, 1, 2],
              [6, 4, 5]])
print(np.sort(b))

Sorting in reverse

import numpy as np
a = np.array([3, 1, 4, 1, 5])
print(np.sort(a)[::-1])   # descending

💡 Tip: to sort descending, sort normally then reverse with [::-1].

Try it Yourself
Output

          
Ad · responsive