Sorting and Ranking
Two different questions: sort vs rank
Section titled “Two different questions: sort vs rank”- Sorting rearranges rows so they appear in order.
- Ranking assigns each value a position number (1st, 2nd, 3rd…) without rearranging anything — the rank becomes a new column or Series aligned to the original order.
Both are everyday analytics needs: sorting a leaderboard, ranking students by score.
Sorting by index: sort_index
Section titled “Sorting by index: sort_index”import pandas as pd
import numpy as np
obj = pd.Series([4, 7, -3, 2, np.nan], index=["d", "a", "c", "b", "e"])
print(obj.sort_index()) # sorted lexicographically by labelSorting by value: sort_values
Section titled “Sorting by value: sort_values”print(obj.sort_values())Missing values sort to the end by default. Use na_position="first" to flip that:
print(obj.sort_values(na_position="first"))Sorting a DataFrame by one or more columns
Section titled “Sorting a DataFrame by one or more columns”frame = pd.DataFrame({"b": [4, 7, -3, 2], "a": [0, 1, 0, 1]})
print(frame.sort_values("b")) # single column
print(frame.sort_values(["a", "b"])) # tie-break: sort by "a" first, then "b"Ranking: rank()
Section titled “Ranking: rank()”rank() assigns each value a position from 1 through the number of valid points,
starting at the lowest value. Ties are handled by averaging their ranks by default:
s = pd.Series([7, -5, 7, 4, 2, 0, 4])
print(s.rank())Both 7s tie for ranks 6 and 7, so they each get the average, 6.5. Other tie-break
rules are available via method:
print(s.rank(method="first")) # ties broken by order of appearance
print(s.rank(method="min")) # ties get the lowest rank in the group
print(s.rank(ascending=False)) # rank from highest to lowest insteadmethod | What it does |
|---|---|
"average" | Default — tied values share the mean rank |
"min" | Tied values all get the lowest rank in the group |
"max" | Tied values all get the highest rank in the group |
"first" | Ties broken by the order values appear in the data |
"dense" | Like "min", but ranks always increase by exactly 1 between groups |
Common pitfalls
Section titled “Common pitfalls”sort_values()on a Series withNaNputs them last — easy to miss if you don’t scroll to the bottom of a big result.rank()’s default"average"method can produce fractional ranks (6.5) — if you need whole-number ranks for display, usemethod="first"ormethod="dense".- Sorting returns a new object; it doesn’t sort in place unless you pass
inplace=True(and even then, prefer reassigning — it’s clearer).
Visualize it
Section titled “Visualize it”flowchart LR A["Unsorted values"] -->|"sort_values()"| B["Rows physically reordered"] A -->|"rank()"| C["Same row order,
each value gets a rank number"]
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Sort a Series by Value
Section titled “Exercise 1 – Sort a Series by Value”Exercise 2 – Put Missing Values First
Section titled “Exercise 2 – Put Missing Values First”Exercise 3 – Rank Values With Averaged Ties
Section titled “Exercise 3 – Rank Values With Averaged Ties”Sorting rearranges rows you already have. Applying Functions (apply, map, applymap) covers transforming the values inside those rows.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading