NumPy Array Sort
Sorting a NumPy array arranges its elements in order using np.sort(), which works seamlessly across one and multi-dimensional arrays.
Sorting with np.sort()
np.sort() returns a new, sorted copy of an array and leaves the original array untouched. This is different from the .sort() method on a Python list, which sorts in place. NumPy's approach is safer by default since you don't accidentally lose the original ordering, though NumPy arrays also have their own in-place .sort() method if you want to modify the array directly.
Example
import numpy as np
arr = np.array([42, 7, 19, 3, 88])
# np.sort() returns a new sorted array
sorted_arr = np.sort(arr)
print(sorted_arr)
# [ 3 7 19 42 88]
print(arr)
# [42 7 19 3 88] (original is unchanged)
# Descending order: sort ascending, then reverse
print(sorted_arr[::-1])
# [88 42 19 7 3]
# In-place sort modifies the array directly
arr.sort()
print(arr)
# [ 3 7 19 42 88]Sorting 2D Arrays
When you call np.sort() on a 2D array without specifying an axis, it sorts along the last axis by default — meaning each row is sorted independently. Passing axis=0 instead sorts each column independently (down the rows), and axis=None flattens the array first and returns a single sorted 1D array.
Example
import numpy as np
matrix = np.array([[3, 1, 2],
[9, 7, 8],
[6, 4, 5]])
# Default axis=-1 sorts each row independently
print(np.sort(matrix))
# [[1 2 3]
# [7 8 9]
# [4 5 6]]
# axis=0 sorts each column independently
print(np.sort(matrix, axis=0))
# [[3 1 2]
# [6 4 5]
# [9 7 8]]Sorting Strings and Getting Sort Order
np.sort() works just as well on arrays of strings, sorting alphabetically. When you need the order rather than the sorted values themselves — for example, to sort one array based on the values of another — use np.argsort(), which returns the indices that would sort the array.
Example
import numpy as np
names = np.array(['Diana', 'Amir', 'Chen', 'Beth'])
print(np.sort(names))
# ['Amir' 'Beth' 'Chen' 'Diana']
# argsort returns the indices that would sort the array
scores = np.array([88, 95, 70, 82])
order = np.argsort(scores)
print(order)
# [2 3 0 1]
# Use those indices to reorder a related array of names
print(names[order])
# ['Chen' 'Beth' 'Diana' 'Amir'] (names lined up with ascending scores)- There is no descending=True argument — reverse a sorted array with [::-1] or negate values before sorting.
- The kind parameter lets you choose the sorting algorithm ('quicksort', 'mergesort', 'heapsort', 'stable'); 'stable' preserves the relative order of equal elements.
- np.argsort() is the key to 'sort one array by the order of another' — sort the indices of the reference array, then index the target array with them.
- Sorting a 2D array with axis=0 sorts each column independently, which is different from sorting the array as if it were a table of rows.
Exercise: NumPy Array Sort
What happens to the original array when you call np.sort(arr)?