In pandas, how does DataFrame.nlargest differ from sort_values followed by head, and what does its keep argument decide?
answer
- select without a full sort
- ties at the cut-off
- first, last or all
- can return more than n
- numeric and datetime columns only
basics
~10 sdf.nlargest(3, 'revenue') returns the three highest-revenue rows, like a descending sort then head(3) but without sorting every row; keep chooses which tied rows win the last places ('first', 'last') or keeps every tie ('all').
solid answer
~40 s`df.nlargest(n, columns, keep='first')` returns the `n` rows with the largest values in `columns`, in descending order, with all other columns attached; `nsmallest` is the mirror. The docstring calls it equivalent to `sort_values(columns, ascending=False).head(n)` but more performant, because it selects the top rows instead of ordering all of them. `keep` settles ties at the cut-off: `'first'` prefers earlier rows, `'last'` later rows, and `'all'` keeps every row tied with the n-th value, so the result can exceed `n`. It only accepts numeric or datetime-like columns: object, category and pandas 3.0's default `str` columns raise `TypeError`. In pandas 3.0 `Series.nlargest` sorts stably internally, so equal values come back in their original order.
code
python · 15 linesimport pandas as pd
products = pd.DataFrame({
"product": ["Kettle", "Mixer", "Toaster", "Juicer", "Blender"],
"revenue": [900, 700, 700, 500, 700],
})
print(products.nlargest(2, "revenue"))
print(products.nlargest(2, "revenue", keep="last"))
print(products.nlargest(2, "revenue", keep="all"))
try:
products.nlargest(2, "product")
except TypeError as err:
print(err)go deeper
Remember nlargest(n, column) for a quick top n, and that nsmallest is its mirror.
Explain the equivalence to a descending sort plus head, why nlargest is faster on big frames, and what each keep option does at the cut-off.
Show the edge cases that break reports: keep='all' returning more than n, the TypeError on text columns, ties against sort-then-head, and the 3.0 stable ordering.
Decide how a team reports ties in top-n outputs, fixed count or every tied row, and make that choice explicit in shared code.
## What `nlargest` returns `DataFrame.nlargest(n, columns, keep="first")` answers "give me the top n rows by this column" for a pandas DataFrame: - It returns a **DataFrame** of at most `n` rows (more with `keep="all"`), ordered by `columns` from largest to smallest. - Every other column comes along unchanged; only `columns` decides the order. - Index labels are kept, just as with `sort_values`. - `DataFrame.nsmallest` is the mirror image, and `Series.nlargest(n)` / `Series.nsmallest(n)` do the same on one column. The docstring describes `df.nlargest(n, cols)` as equivalent to `df.sort_values(cols, ascending=False).head(n)`, **but more performant**. Instead of ordering every row, it finds the cut-off value and sorts only the candidates that reach it. On a frame of millions of rows where you want ten, that saving is real; on a small frame the two are interchangeable in speed. ## `keep`: who wins a tie at the cut-off Ties only matter at the boundary — when the n-th place is shared by several rows. With revenues `[900, 700, 700, 500]` and `n=2`: | `keep` | rows returned | rule | |---|---|---| | `'first'` (default) | 900 and the **first** 700 | prefer earlier occurrences | | `'last'` | 900 and the **second** 700 | prefer later occurrences; ties are listed in reverse order | | `'all'` | 900 and **both** 700s — three rows | keep every row tied with the n-th value | Two consequences of `keep="all"` are worth saying in an interview: 1. The result can be **longer than n**. Code that assumes exactly three rows — say, to fill a fixed "top three products" layout — breaks on a tie. 2. It does **not** return the n largest **distinct** values. The docstring's own example shows `nlargest(5, ..., keep="all")` returning five rows that share only three distinct values. ## Several columns `columns` can be a list: `df.nlargest(3, ["revenue", "units"])` orders by revenue and uses units to decide among equal revenues — the same priority rule as a multi-key `sort_values`. `keep` then applies to rows that tie on every listed column. ## Where it differs from `sort_values(...).head(n)` - **Ties.** The documented equivalence is only exact up to ties. A plain `sort_values(ascending=False)` uses the default unstable algorithm, so which of several tied rows lands in the last slot is not guaranteed. `sort_values(..., ascending=False, kind="stable").head(n)` gives the same rows as `keep="first"`. - **Dtypes.** `nlargest` accepts **numeric** (but not complex) and **datetime-like** columns only. A text or categorical column raises `TypeError` naming the column and its dtype — for example `Column 'product' has dtype str, cannot use method 'nlargest' with this dtype`. `sort_values` sorts text happily. - **Missing values.** NaN never outranks a real value: missing rows come after every real value and only appear when `n` exceeds the number of non-missing rows. ## Choosing between them - Reach for **`nlargest`** for a plain top n of a large numeric or datetime column, where it avoids ordering every row. - Reach for **`sort_values(...).head(n)`** when you also need the full order for something else, when the key is text, or when you want the tie rule spelled out with an explicit second key and `kind="stable"`. - Reach for **`rank`** when every row should keep its place in the frame and receive a position number instead of being filtered. Whichever you choose, say how ties are handled; it is the first follow-up an interviewer asks. ## What changed in pandas 3.0 - `Series.nlargest` now uses a **stable sort internally**, so equal values come back in their original order. Earlier releases made no such promise about the order of equal values in the result. - Text columns now infer the `str` dtype rather than object; `nlargest` rejects both, so the `TypeError` above is what a 3.0 user sees when pointing it at a product-name column. ## Common slips - Assuming `keep="all"` returns exactly `n` rows. - Calling `nlargest` on a column of numbers stored as text and getting a `TypeError`; convert with `pd.to_numeric` first. - Expecting `nlargest(3, "revenue")` to return the three largest distinct revenues. - Forgetting that ranking **within** each group is a groupby operation, not `nlargest` on the whole frame.
- A dashboard needs exactly three products. Is keep='all' safe there?No. `keep='all'` returns every row tied with the third value, so a tie at the cut-off yields four or more rows. Use `keep='first'` (or `'last'`) for a fixed count, and add a second column to `columns` if ties need a meaningful tie-breaker rather than input order.
- How do you get the three largest distinct revenues instead of three rows?`nlargest` works on rows, not distinct values. Take the distinct values first, for example `df['revenue'].drop_duplicates().nlargest(3)`, then filter rows with `isin` if you need every row at those revenues.
- Why does nlargest raise TypeError on a column read from a file as text?`nlargest` only accepts numeric or datetime-like dtypes. A column of digits stored as text has the `str` dtype in pandas 3.0 (object in 2.x), which it rejects. Convert with `pd.to_numeric(df['revenue'])` and call it again.
- nlargest always returns exactly n rows
- keep='all' returns the n largest distinct values
- nlargest works on any column that sort_values can sort
- sort_values with ascending=False then head(n) always picks the same tied rows as nlargest
- NaN counts as the largest value in nlargest
Assumes pandas 3.0: Series.nlargest now sorts stably so equal values keep their original order, and text columns infer the str dtype, which nlargest rejects as it rejected object in 2.x.