Top N Values
Finding the largest or smallest values is a common operation. Pandas provides efficient methods for this.
nlargest() and nsmallest()
Get the top or bottom N rows:
Loading Pandas Playground...
vs. sort_values().head()
nlargest and nsmallest are more efficient:
Loading Pandas Playground...
Multiple Columns
Specify tie-breaker columns:
Loading Pandas Playground...
Series nlargest/nsmallest
Also works on Series:
Loading Pandas Playground...
Combining with Other Operations
Find top N within groups or after filtering:
Loading Pandas Playground...
Using idxmax() and idxmin()
Find the index of max/min values:
Loading Pandas Playground...
Exercise: Top Products
Loading Exercise...
Exercise: Find Maximum
Loading Exercise...
Key Points
nlargest(n, column)gets top N rowsnsmallest(n, column)gets bottom N rows- More efficient than
sort_values().head() - Works on both DataFrames and Series
idxmax()/idxmin()find index of max/min- Can use multiple columns for tie-breaking

