Sorting Arrays
Sort values with np.sort (returns a copy) or ndarray.sort (in place), sort in descending order, and sort 2D arrays along rows, columns or the whole array.
"Show me Virat's innings from lowest to highest." "List every score of the season, best first." Sorting is one of the first things an analyst does with data, and NumPy sorts arrays in fast compiled code — far faster than sorting a Python list for large data.
Definition
Sorting rearranges the elements of an array into ascending order (smallest first).
np.sort(a)returns a sorted copy and leavesaunchanged;a.sort()sorts the array in place (changesaitself) and returnsNone. For multi-dimensional arrays, both sort independently along one axis (the last axis by default).
- Ascending only — NumPy has no
reverse=Trueoption. Descending order is done by reversing the result ([::-1]) or sorting the negative values. - Copy vs in place — the same difference as Python's
sorted(lst)vslst.sort(). - Along one axis — each row (or each column) is sorted on its own; rows are not kept together. To reorder whole rows by one column, use
argsort(next topic).
Syntax
python
np.sort(a, axis=-1, kind=None, order=None, *, stable=None) # returns a new array
a.sort(axis=-1, kind=None, order=None, *, stable=None) # in place, returns None| Parameter | Meaning | Default |
|---|---|---|
a | the array to sort | required |
axis | axis to sort along. -1 = last axis (each row of a 2D array), 0 = each column, None = flatten then sort (np.sort only) | -1 |
kind | algorithm: "quicksort", "mergesort", "heapsort", "stable" | None (quicksort / introsort) |
order | field name(s) to sort by, for structured arrays | None |
stable | True = equal values keep their original order | None |
Example — np.sort vs ndarray.sort
python
import numpy as np
runs = np.array([72, 45, 88, 31, 64, 0, 103])
s = np.sort(runs)
print(s)
print(runs)
r = runs.copy()
out = r.sort()
print(r)
print(out)text
[ 0 31 45 64 72 88 103]
[ 72 45 88 31 64 0 103]
[ 0 31 45 64 72 88 103]
NoneHow it works: np.sort gave a new sorted array and runs kept its original match order. r.sort() rearranged r itself and returned None. Use np.sort when the original order still matters (here it does — the order is the match sequence!).
Example — descending order
python
print(np.sort(runs)[::-1])
print(-np.sort(-runs))text
[103 88 72 64 45 31 0]
[103 88 72 64 45 31 0]How it works: [::-1] reverses the ascending result (a cheap view). -np.sort(-runs) sorts the negatives ascending, then flips the sign back — handy for numbers, but it does not work for strings.
Example — sorting a 2D array along an axis
python
squad = np.array([[72, 45, 88, 31], # Virat
[56, 0, 74, 88], # Rohit
[45, 32, 0, 67]]) # Hardik
print(np.sort(squad)) # axis=-1: each ROW sorted
print(np.sort(squad, axis=0)) # each COLUMN sorted
print(np.sort(squad, axis=None)) # everything, flattenedtext
[[31 45 72 88]
[ 0 56 74 88]
[ 0 32 45 67]]
[[45 0 0 31]
[56 32 74 67]
[72 45 88 88]]
[ 0 0 31 32 45 45 56 67 72 74 88 88]How it works:
text
axis=1 / -1 -> sort along each row (each player's scores, low to high)
axis=0 -> sort down each column (each match's scores, low to high)
axis=None -> flatten, then sort (every score of the season)Notice that with axis=0 the rows are mixed up: the first row [45 0 0 31] is not any real player — it is the lowest score of each match. Sorting along an axis sorts every row/column independently.
For each player's scores best first, sort the rows then reverse the columns:
python
print(np.sort(squad, axis=1)[:, ::-1])text
[[88 72 45 31]
[88 74 56 0]
[67 45 32 0]]Sorting strings and NaN
python
names = np.array(["Rohit", "virat", "Bumrah", "Dhoni", "Gill"])
print(np.sort(names))
print(np.sort(np.array([3.5, np.nan, 1.0, 2.0])))text
['Bumrah' 'Dhoni' 'Gill' 'Rohit' 'virat']
[1. 2. 3.5 nan]Strings sort alphabetically by character code, so uppercase comes before lowercase ('virat' lands last). NaN values are always placed at the end.
Python list vs NumPy
| Python list | NumPy array | |
|---|---|---|
| sorted copy | sorted(lst) | np.sort(arr) |
| in place | lst.sort() → None | arr.sort() → None |
| descending | sorted(lst, reverse=True) | np.sort(arr)[::-1] |
| custom key | key=len | no key — use argsort on a computed array |
| 2D | — | axis=0 / 1 / None |
| speed | Python objects | compiled C — much faster for big arrays |
Common mistakes
- ❌
sorted_runs = runs.sort()→sorted_runsisNone. ✅sorted_runs = np.sort(runs). - ❌
np.sort(runs, reverse=True)→TypeError. ✅np.sort(runs)[::-1]. - ❌ Sorting a 2D table with
axis=0and expecting rows to stay together. ✅ Each column is sorted separately; useargsortto reorder whole rows. - ❌
arr.sort()on the only copy of match-ordered data. ✅ Usenp.sort(or.copy()first) so the original order survives.
Interview tip
Q: What is the difference between np.sort(a) and a.sort()?
A: np.sort(a) returns a new sorted copy and leaves a unchanged. a.sort() sorts a in place, uses no extra array, and returns None. np.sort also accepts axis=None to flatten first.
Key points to remember
- np.sort(a) returns a sorted copy; a.sort() sorts in place and returns None.
- NumPy sorts ascending only — use np.sort(a)[::-1] (or -np.sort(-a) for numbers) for descending.
- For 2D arrays the default axis=-1 sorts each row; axis=0 sorts each column; axis=None flattens and sorts everything.
- Sorting along an axis sorts every row/column independently — rows are not kept together.
- Strings sort by character code (uppercase before lowercase); NaN always goes to the end.
- kind='stable' keeps equal values in their original order.
Try it yourself
Copy vs in place, ascending vs descending
Sorting a 2D squad table along each axis
Practice: season scores best to worst
Revision Flashcards
Tap a card to flip it and see the answer.
