0
0
Pandasdata~5 mins

nlargest() and nsmallest() in Pandas

Choose your learning style9 modes available
Introduction

These functions help you quickly find the biggest or smallest values in your data. They make it easy to see top or bottom results without sorting everything.

Finding the top 3 highest sales days in a store.
Getting the 5 smallest temperatures recorded in a week.
Selecting the top 10 students with highest scores in a test.
Finding the lowest 2 prices of products in a list.
Syntax
Pandas
DataFrame.nlargest(n, columns, keep='first')
DataFrame.nsmallest(n, columns, keep='first')

n is how many top or bottom rows you want.

columns is the column name or list of columns to sort by.

Examples
Get 3 rows with highest values in 'score' column.
Pandas
df.nlargest(3, 'score')
Get 2 rows with smallest 'age', and if tie, smallest 'score'.
Pandas
df.nsmallest(2, ['age', 'score'])
Sample Program

This code creates a small table of people with their scores and ages. Then it finds the 2 highest scores and the 3 youngest people.

Pandas
import pandas as pd

data = {'name': ['Anna', 'Bob', 'Cara', 'Dave', 'Eva'],
        'score': [88, 92, 85, 95, 90],
        'age': [23, 25, 22, 24, 23]}
df = pd.DataFrame(data)

# Find top 2 scores
top_scores = df.nlargest(2, 'score')

# Find 3 smallest ages
smallest_ages = df.nsmallest(3, 'age')

print('Top 2 scores:')
print(top_scores)
print('\n3 smallest ages:')
print(smallest_ages)
OutputSuccess
Important Notes

If there are ties, keep='first' keeps the first rows found.

You can use multiple columns to break ties by passing a list.

Summary

nlargest() gets rows with highest values in a column.

nsmallest() gets rows with lowest values in a column.

Both help quickly find top or bottom data without full sorting.