Top-k minimum selection
Find the lowest-valued records in a DataFrame without sorting the entire table.
Pandas · Module
Returns the first n DataFrame rows with the smallest values in one or more columns, ordered ascending. Other columns are included but do not influence ranking.
Call nsmallest with a row count and one or more ordering columns. It returns the selected rows in ascending order, retaining every DataFrame column; when values tie, keep controls which occurrences are retained.
DataFrame.nsmallest(n, columns, keep='first')| Name | Type | Description |
|---|---|---|
n | int | Number of items to retrieve. |
columns | list or str | Column name or names to order by. |
keep | {'first', 'last', 'all'}, default 'first' | Tie behavior: 'first' keeps the first occurrence, 'last' the last occurrence, and 'all' every tie at the boundary; defaults to 'first'. |
DataFrame with the first n rows ordered by columns in ascending order.
import pandas as pd
df = pd.DataFrame({
"city": ["A", "B", "C", "D"],
"population": [120, 80, 80, 200],
"gdp": [4, 7, 3, 9],
})
result = df.nsmallest(2, ["population", "gdp"], keep="first")
print(result)Selects the two rows with the smallest population, breaking ties by GDP.
Find the lowest-valued records in a DataFrame without sorting the entire table.
Rank by a primary metric and use additional columns to break ties.
Retain every record tied at the cutoff rather than forcing exactly n rows.
DataFrame.nsmallest(n, columns, keep='first') returns the first n rows ordered by the specified columns in ascending order. It includes unspecified columns in the result, but those columns do not affect ordering.
Follow-up: How would you reproduce it without nsmallest? Use df.sort_values(columns, ascending=True).head(n), although the documentation notes nsmallest is more performant.
n is the number of items to retrieve, while columns is a column name or a list of names used for ordering. Multiple columns apply successive ordering criteria, so later columns resolve ties from earlier ones.
Follow-up: What happens if the ordering columns are omitted? The call is invalid because both n and columns are required positional arguments in the documented signature.
keep determines duplicate handling: first keeps the first occurrence, last keeps the last occurrence, and all keeps every tie at the boundary. Therefore keep='all' may produce more than n rows.
Follow-up: Why might keep='all' be useful? It preserves every row tied at the cutoff instead of arbitrarily dropping tied rows.
DataFrame.nlargestDataFrame.sort_valuesDataFrame.headSeries.nsmallest