In pandas, how do you keep the top two products by revenue in each store, and why prefer sort_values then groupby head over apply with nlargest?
answer
- sort once, then take
- head is a filtration
- original labels survive
- ties at the cutoff
- rank method decides ties
basics
~10 sSort by revenue descending, then call groupby('store').head(2). head is a vectorized filtration that returns the original rows, labels and columns; apply(lambda g: g.nlargest(2, 'revenue')) runs Python per store and adds a store index level.
solid answer
~40 s`df.sort_values('revenue', ascending=False).groupby('store').head(2)` sorts once and then keeps the first two rows of each store in the current order. `head` is a GroupBy **filtration**: it returns a subset of the original rows with their original labels and columns, `store` included, ignores `as_index`, and adds no key to the index. `df.groupby('store').apply(lambda g: g.nlargest(2, 'revenue'))` gives the same rows when nothing ties, but calls a Python function per store and, with the default `group_keys=True`, returns a MultiIndex of store and original label. Ties need a decision: `head(2)` takes exactly two in sort order (use `kind='stable'` to make that the input order), while `rank(method='min', ascending=False) <= 2` keeps every product tied at second place.
code
python · 14 linesimport pandas as pd
sales = pd.DataFrame({
"store": ["S1", "S1", "S1", "S2", "S2", "S2"],
"product": ["tea", "milk", "bread", "tea", "jam", "eggs"],
"revenue": [500, 900, 700, 700, 900, 700],
})
top2 = (sales.sort_values("revenue", ascending=False, kind="stable")
.groupby("store")
.head(2))
print(top2)
r = sales.groupby("store")["revenue"].rank(method="min", ascending=False)
print(sales[r <= 2])go deeper
Recall the pattern: sort by the value descending, then groupby the key and take head(n). The sort is what makes it the top n.
Explain why head is a filtration that keeps original labels and columns, and how its result differs from apply with nlargest.
Show that you settle the tie rule explicitly, choosing head with a stable sort, rank with method first or min, or nlargest with keep='all', and avoid per-group apply on large data.
Make tie handling in ranked reports a stated, shared rule so that two teams' top-two lists for the same data cannot disagree.
## The idiomatic pattern "Top N per group" is one of the most common grouped requests: the two best-selling products in each store, the three latest orders per customer, the highest score per student. In pandas the standard answer has two steps: ```python top2 = (sales.sort_values("revenue", ascending=False) .groupby("store") .head(2)) ``` 1. **Sort once** across the whole frame, so that within every store the rows are in descending revenue order. groupby preserves the order of rows inside each group, so the sort carries through. 2. **Take the first n per group** with `GroupBy.head(n)`, which builds a positional mask for all groups at once. `GroupBy.head` is documented as similar to `.apply(lambda x: x.head(n))` "but it returns a subset of rows from the original DataFrame with original index and order preserved (`as_index` flag is ignored)". The user guide lists `head`, `tail` and `nth` as **filtrations**, methods with an efficient GroupBy-specific implementation that return rows rather than a summary. ## What each approach returns | approach | index of the result | `store` column | per-store Python call | |---|---|---|---| | `sort_values(...).groupby('store').head(2)` | original labels, in sorted order | kept | no | | `groupby('store').apply(lambda g: g.nlargest(2, 'revenue'))` | MultiIndex: store, original label | in the outer index level | yes | | `groupby('store')['revenue'].nlargest(2)` | MultiIndex: store, original label | revenue Series only | yes, internally | | `df[g['revenue'].rank(method='first', ascending=False) <= 2]` | original labels, original order | kept | no | The `head` and `rank` forms return rows that can be joined, assigned or written out without index surgery. The `apply` form usually needs `reset_index` or `droplevel` before it lines up with anything else, and its cost grows with the number of stores because each one is a separate Python call. `SeriesGroupBy.nlargest` is also implemented as a per-group loop, so it is convenient rather than fast. ## Ties at the cutoff The approaches pick different rows only when values tie, and that is where the business rule has to be explicit. Consider a store whose products earn 900, 700 and 700: - `head(2)` after sorting keeps **exactly two**: the 900 and whichever 700 the sort put first. The default sort algorithm is not stable, so pass `kind='stable'` to keep the input order among ties, or sort by a second column (`['revenue', 'product']`) to make the choice deterministic. - `rank(method='first', ascending=False) <= 2` also keeps exactly two, numbering ties in order of appearance. - `rank(method='min', ascending=False) <= 2` gives ranks 1, 2, 2 and keeps **all three**, the right answer when tied products should share second place. - `rank(method='dense', ...)` also gives 1, 2, 2 here, but differs from `'min'` after a tie at the top. - `nlargest(2, 'revenue', keep='all')` similarly keeps every row tied with the last place. Whichever you choose, write the tie rule into the code and the report, because "top two" with ties is not a well-defined set until someone says what happens at the edge. ## Why the head pattern is preferred - **Speed**: one global sort plus a vectorized mask, rather than a function call, an object build and a concatenation per store. - **Shape**: original rows with original labels and every column, ready for further work. - **Predictability**: no dependence on how `apply` infers the result shape or on which columns `apply` passes to the function. ## Related positional filtrations `head` has two siblings that follow the same rules. `tail(n)` keeps the last n rows of each group, which after a descending sort gives the bottom n. `nth(k)` keeps the row at position k of each group, counting from 0 and accepting negative positions, lists and slices: after a descending sort, `nth(1)` is each store's second-best product, and a store with only one product simply contributes no row rather than raising an error. All three return original rows with original labels. ## Pitfalls - Calling `groupby('store').head(2)` **without** sorting first: it returns the first two rows of each store in file order, not the top two by anything. - Sorting ascending and taking `head`: that yields the bottom two; use `tail(2)` or sort descending. - Expecting the result grouped by store: rows come back in the sorted frame's order, so add `.sort_values(['store', 'revenue'], ascending=[True, False])` for a readable report. - Expecting `nth(0)` to return a per-store summary indexed by store: like `head(1)`, it is a filtration that returns original rows. Ranking options on an ungrouped column, such as `pct` and `na_option`, belong with pandas sorting and ranking.
- How do you get only the single best product per store with its full row?Sort by revenue descending and call `groupby('store').head(1)`, or use `df.loc[df.groupby('store')['revenue'].idxmax()]`, which looks up each store's best row by label. Both return full rows; `idxmax` picks the first label among ties, so state that rule if ties are possible.
- Why does df.groupby('store').head(2) on an unsorted frame look plausible but answer the wrong question?`head` takes the first rows of each group in the frame's current order. If the file happened to be sorted by date, you get each store's two earliest sales, which looks like a valid result. Always sort by the ranking column, and a tie-breaker, immediately before the grouped `head`.
- groupby head(2) returns the two largest values in each group
- apply with nlargest is the fastest way to take top N per group
- head after a groupby returns a store-keyed MultiIndex like apply does
- Top two per group is always exactly two rows, whatever the ties
- rank defaults to method='first', so ties never share a rank