Top-N selection
Ranking records by a numeric metric
Pandas · Module
Returns the rows with the largest values in specified DataFrame columns, ordered descending. It supports configurable handling of ties through keep.
Call DataFrame.nlargest to return rows ordered by one or more columns from largest to smallest. It retains all DataFrame columns, uses only the named columns for ordering, and provides explicit tie policies through keep.
DataFrame.nlargest(n, columns, keep='first')| Name | Type | Description |
|---|---|---|
n | int | Number of rows to return. |
columns | Hashable or a sequence | Column label or sequence of column labels to order by. |
keep | {'first', 'last', 'all'}, default 'first' | Duplicate-value policy: first, last, or all; defaults to first. |
DataFrame containing the first n rows ordered by the specified columns in descending order.
n rows after descending ordering.keep="first" favors earlier rows when ordering values tie.keep="last" resolves equal values by favoring later occurrences.keep="all", the result can contain more than n rows.import pandas as pd
df = pd.DataFrame({
"name": ["Ada", "Grace", "Linus", "Edsger"],
"score": [91, 98, 87, 98],
})
print(df.nlargest(2, "score"))
print(df.nlargest(2, "score", keep="all"))Select the two highest-scoring rows; the second call retains every row tied at the cutoff.
Ranking records by a numeric metric
Including every record tied at the boundary
Ordering by multiple sortable columns
DataFrame.nlargest return?It returns the first n rows ordered by the selected columns in descending order. Unlike selecting only the ordering columns, it returns the other DataFrame columns too.
Follow-up: How would you express the same operation with general sorting? Use df.sort_values(columns, ascending=False).head(n), although the documentation notes that nlargest is more performant.
n and columns?columns identifies the column label or sequence of labels used for ordering. n specifies how many rows to return.
Follow-up: What happens to non-selected columns? They remain in the returned DataFrame but do not participate in ordering.
keep affect duplicate values?keep="first" prioritizes first duplicate occurrences, keep="last" prioritizes last occurrences, and keep="all" preserves ties at the cutoff even when that exceeds n rows.
Follow-up: Which option should be used when every tied row must be included? Use keep="all".
DataFrame.sort_values