Skip to main content

MATH 345: Linear Algebra and Optimization

Section B.6 Sorting and Rankings

This section helps you read sorting commands as requests for positions and rankings.
scores = np.array([0.2, 0.9, 0.5])
doc_names = np.array(["D0", "D1", "D2"])

np.argsort(scores)        # indices from smallest score to largest
np.argsort(scores)[::-1]  # indices from largest score to smallest
np.argmax(scores)         # index of the largest score

ranking = doc_names[np.argsort(scores)[::-1]]

Sorting positions.

np.argsort(scores)
Read as. Indices from smallest score to largest score.
Shape/return. An index array.
Used for. Sorting.

Largest-value position.

np.argmax(scores)
Read as. The index of the largest entry of scores.
Shape/return. An integer index.
Used for. Locating a sampled maximum.
Watch for. This returns a position, not the largest value itself. If several entries tie for largest, NumPy returns the first such position.

Reverse ranking.

np.argsort(scores)[::-1]
Read as. Indices from largest score to smallest score.
Shape/return. An index array.
Used for. Rankings.

Reordered names.

doc_names[...]
Read as. Select or reorder names by indices.
Shape/return. A reordered array.
Used for. Document ranking.

Warning B.6.1. Sorted positions are not sorted scores.

np.argsort(scores) returns positions, not sorted scores.