Skip to content

Sorting and Ranking

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

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 label
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 label

Sorting by value: sort_values

sort_values
print(obj.sort_values())
sort_values
print(obj.sort_values())

Missing values sort to the end by default. Use na_position="first"na_position="first" to flip that:

Controlling where NaN lands
print(obj.sort_values(na_position="first"))
Controlling where NaN lands
print(obj.sort_values(na_position="first"))

Sorting a DataFrame by one or more columns

Sort a DataFrame by column values
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"
Sort a DataFrame by column values
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()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:

rank() with default tie-breaking
s = pd.Series([7, -5, 7, 4, 2, 0, 4])
print(s.rank())
rank() with default tie-breaking
s = pd.Series([7, -5, 7, 4, 2, 0, 4])
print(s.rank())

Both 77s tie for ranks 6 and 7, so they each get the average, 6.56.5. Other tie-break rules are available via methodmethod:

Tie-breaking methods
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 instead
Tie-breaking methods
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 instead
methodmethodWhat it does
"average""average"Default — tied values share the mean rank
"min""min"Tied values all get the lowest rank in the group
"max""max"Tied values all get the highest rank in the group
"first""first"Ties broken by the order values appear in the data
"dense""dense"Like "min""min", but ranks always increase by exactly 1 between groups

Common pitfalls

  • sort_values()sort_values() on a Series with NaNNaN puts them last — easy to miss if you don’t scroll to the bottom of a big result.
  • rank()rank()’s default "average""average" method can produce fractional ranks (6.56.5) — if you need whole-number ranks for display, use method="first"method="first" or method="dense"method="dense".
  • Sorting returns a new object; it doesn’t sort in place unless you pass inplace=Trueinplace=True (and even then, prefer reassigning — it’s clearer).

Visualize it

diagram Sort vs rank mermaid
sort_values rearranges rows into order; rank keeps the original row order but attaches a position number to each value.
sketch Bars reordering by sort_values p5.js
The faded bars show the original order; the solid bars show the same values after sort_values() rearranges them ascending.

🧪 Try It Yourself

Exercise 1 – Sort a Series by Value

Exercise 2 – Put Missing Values First

Exercise 3 – Rank Values With Averaged Ties

Next

Sorting rearranges rows you already have. Applying Functions (apply, map, applymap) covers transforming the values inside those rows.

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did