Skip to main content
Albero Academy

Sorting

Order rows by one or more columns, and grab the top/bottom N.

Selecting & Filtering7 min

Sorting orders rows by column values — for reports, rankings, or just to see the extremes. Pandas sorts by one or several columns and has shortcuts for the top and bottom rows.

sort_values

order rows
df.sort_values("package", ascending=False) # highest package first
df.sort_values(["programme", "package"], # by two keys
ascending=[True, False])
df.sort_index() # sort by the index instead

Top and bottom N

nlargest / nsmallest
df.nlargest(5, "package") # top 5 by package (faster than sort+head)
df.nsmallest(3, "package") # bottom 3

Key takeaways

  1. 01sort_values(col) orders rows; pass a list for multi-key sorts with per-key ascending.
  2. 02sort_index() orders by the index instead of a column.
  3. 03nlargest/nsmallest grab the top/bottom N efficiently.
  4. 04Sorting returns a new DataFrame — assign it or chain on.

Finished this chapter?

Mark it complete to track your progress through Pandas.