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
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
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
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()
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
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
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
Exercise 1 – Sort a Series by Value
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 2 – Put Missing Values First
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 3 – Rank Values With Averaged Ties
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Check your understanding
Where do missing values land in obj.sort_values() by default?
NaN sorts last by default. Use na_position="first" to flip that.
Show answer
A — At the end — NaN sorts last by default. Use na_position="first" to flip that.
For s = pd.Series([7, -5, 7, 4, 2, 0, 4]), what rank does each 7 get with the default rank()?
The two 7s tie for ranks 6 and 7, and the default method averages tied ranks to 6.5.
Show answer
A — 6.5 — The two 7s tie for ranks 6 and 7, and the default method averages tied ranks to 6.5.
For the same Series, what does s.rank(method="min") give each 7?
The min method gives every tied value the lowest rank in its group, which for the 7s is 6.
Show answer
A — 6.0 — The min method gives every tied value the lowest rank in its group, which for the 7s is 6.
How does frame.sort_values(["a", "b"]) order rows?
The columns are applied in the order listed, so b only breaks ties in a.
Show answer
A — By a first, then by b to break ties — The columns are applied in the order listed, so b only breaks ties in a.
Next
Sorting rearranges rows you already have. Applying Functions (apply, map, applymap) covers transforming the values inside those rows.