Skip to content

Sorting and Ranking

  • 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.

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_values
print(obj.sort_values())

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

Controlling where NaN lands
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”
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"

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())

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

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
methodWhat 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
  • sort_values() on a Series with NaN puts 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, use method="first" or method="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).
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.

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.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading