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
df.sort_values("package", ascending=False) # highest package firstdf.sort_values(["programme", "package"], # by two keysascending=[True, False])df.sort_index() # sort by the index instead
Top and bottom N
df.nlargest(5, "package") # top 5 by package (faster than sort+head)df.nsmallest(3, "package") # bottom 3
Key takeaways
- 01sort_values(col) orders rows; pass a list for multi-key sorts with per-key ascending.
- 02sort_index() orders by the index instead of a column.
- 03nlargest/nsmallest grab the top/bottom N efficiently.
- 04Sorting returns a new DataFrame — assign it or chain on.
