- Sort numbers, strings and booleans with
np.sort(). - Distinguish
np.sort()(returns a copy) fromarr.sort()(in place). - Sort 2-D arrays along rows or columns and in descending order.
- Use
argsort()to sort one array by another.
Sorting Arrays
Sorting arranges elements in an ordered sequence – numeric or alphabetical, ascending or descending. np.sort(arr) returns a sorted copy and leaves the original unchanged.
import numpy as np nums = np.array([42, 7, 19, 3, 25]) print(np.sort(nums)) print(nums) # unchanged names = np.array(["mango", "apple", "kiwi", "banana"]) print(np.sort(names)) # alphabetical flags = np.array([True, False, True, False]) print(np.sort(flags)) # False before True
[ 3 7 19 25 42] [42 7 19 3 25] ['apple' 'banana' 'kiwi' 'mango'] [False False True True]
In-place Sorting: arr.sort()
import numpy as np nums = np.array([42, 7, 19, 3, 25]) result = nums.sort() # sorts the array itself print(nums) print(result) # returns None
[ 3 7 19 25 42] None
Descending Order
NumPy has no reverse=True option. Sort ascending and reverse with [::-1] (or sort the negated numbers).
import numpy as np nums = np.array([42, 7, 19, 3, 25]) print(np.sort(nums)[::-1]) print(-np.sort(-nums))
[42 25 19 7 3] [42 25 19 7 3]
Sorting 2-D Arrays
By default np.sort() sorts along the last axis – each row separately. Use axis=0 to sort each column, and axis=None to flatten and sort everything.
import numpy as np
m = np.array([[9, 2, 7],
[4, 8, 1]])
print(np.sort(m)) # each row
print(np.sort(m, axis=0)) # each column
print(np.sort(m, axis=None)) # all values[[2 7 9] [1 4 8]] [[4 2 1] [9 8 7]] [1 2 4 7 8 9]
argsort(): Indexes that Would Sort
argsort() returns the indexes that would sort the array. It is used to sort one array according to the values of another.
import numpy as np students = np.array(["Asha", "Ravi", "Meera", "John"]) marks = np.array([82, 67, 91, 74]) order = marks.argsort() print(order) print(students[order]) # lowest to highest print(students[order[::-1]][:2]) # top two
[1 3 0 2] ['Ravi' 'John' 'Asha' 'Meera'] ['Meera' 'Asha']
Key Takeaways
np.sort()returns a sorted copy;arr.sort()sorts in place and returns None.- Default axis is the last one (rows of a 2-D array); use
[::-1]for descending order. argsort()gives the sorting order to rearrange related arrays.
Video : Array Sort
Question / Answer (15 questions)
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.
- NumPy Developers. (n.d.). Sorting, searching, and counting. NumPy API Reference. https://numpy.org/doc/stable/reference/routines.sort.html
- NumPy Developers. (n.d.). NumPy quickstart. NumPy User Guide. https://numpy.org/doc/stable/user/quickstart.html
- NumPy Developers. (n.d.). NumPy: the absolute basics for beginners. NumPy User Guide. https://numpy.org/doc/stable/user/absolute_beginners.html
- VanderPlas, J. (2016). Python Data Science Handbook. O’Reilly Media. (Free online edition.) https://jakevdp.github.io/PythonDataScienceHandbook/