nsmallest method in Pandas

In pandas, the nsmallest() method is used to retrieve the first n rows from a DataFrame or Series based on the smallest values in one or more columns.

Syntax DataFrame.nsmallest(n, columns, keep='first')

The function has the following parameters:

Example: With DataFrame.

Python

import pandas as pd

# Sample DataFrame
df = pd.DataFrame({
    'Name': ['Ashish', 'Harsha', 'Chahat', 'Dyna', 'Elina'],
    'Score': [85, 92, 88, 95, 90]
})

# Bottom 2 lowest scores
lowest_scores = df.nsmallest(2, 'Score')

print("\nBottom 2 scores:\n", lowest_scores)

The output of the above code is shown below:

nsmallest method in Pandas

• For Series:

Python

s = pd.Series([10, 40, 30, 20])

s.nsmallest(2)    # Returns 2 smallest values

The output of the above code is shown below:

nsmallest method in Pandas