Numpy allows for easy array sorting. The function np.sort returns a sorted copy of an array, leaving the original array unchanged. A related function is np.argsort, which returns the indices of the sorted elements. This lesson covers NumPy sort, NumPy Argsort, and additional functions you can use to sort a NumPy array.
NumPy Sort
import numpy as np
# standard sorting
a = np.array([2, 1, 4, 3])
# returns the sorted array (a copy)
sorted_array = np.sort(a)
print(sorted_array)
array([1, 2, 3, 4])
NumPy Argsort
# sorting with indices
a = np.array([2, 1, 4, 3])
# Returns the indices that would sort an array.
sorted_indices = np.argsort(a)
print(sorted_indices)
array([1, 0, 3, 2])
How to Sort Arrays In-Place
# in-place sorting
a = np.array([2, 1, 4, 3])
# sorts a in place, returns nothing
a.sort()
print(a)
array([1, 2, 3, 4])
Multi-dimensional Array Sort
# multi-dimensional sorting
a = np.array([[14, 11], [12, 13]])
print(a)
print()
# Sort along the first axis
print(np.sort(a, axis=0))
print()
# Sort along the second axis
print(np.sort(a, axis=1))
[[14 11]
[12 13]]
[[12 11]
[14 13]]
[[11 14]
[12 13]]
Summary: NumPy Sort
- To sort arrays using NumPy sort, use the command
np.sort()to return a sorted copy of an array without altering the original. - Use the NumPy argsort command -
np.argsort()- to return indices that would sort the array. array.sort()sorts the array in-place, changing the original array.- Multi-dimensional arrays can be sorted along specific axes using
np.sort(a, axis=n). This does not alter the original array. - When sorting multi-dimensional arrays, the
axisparameter determines the axis along which the array is sorted. For 2D arrays,axis=0sorts along the rows (which sorts the columns) whileaxis=1sorts along the columns (which sorts the rows).