Select the full row with the maximum value in each group in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `row_of_max_per_group(df, key, val)`. For each group in column `key`, return the full row whose `val` is the largest. The result is a DataFrame with one row per group.
The result must meet these requirements:
- On ties, keep the first occurrence (the same rule `idxmax` uses).
- Keep all original columns of `df`.
- Order the rows by `key` ascending and reset to a fresh `RangeIndex`.
For example:
```python
df = pd.DataFrame({
"key": ["a", "a", "b", "b"],
"val": [3, 7, 5, 5],
"tag": ["x", "y", "z", "w"],
})
row_of_max_per_group(df, "key", "val")
# key val tag
# 0 a 7 y
# 1 b 5 z # first of the tie
```
```hint Keep the whole row
`df.groupby(key)[val].max()` gives the winning value but loses the other columns. Think about what else a per-group reduction could return that lets you look up the full row afterwards.
```
### Constraints & Assumptions
- `df.index` is unique.
### What a Strong Answer Covers
- How the answer keeps every column of the winning row.
- Which row wins a tie, and why the chosen method picks the first occurrence.
- How the output is ordered by `key` and given a fresh index.
- The time and space cost of the approach.
- Edge cases such as missing values in `val` or `key`, and why the unique index matters.
### Follow-up Questions
- How does `idxmax` behave with NaN in `val`, and how would you handle it?
- Why prefer the `idxmax` approach over `sort_values` followed by `drop_duplicates`?
- What if you need the top k rows per group instead of just the maximum?
Overview: Write a pandas function that returns, for each group, the full row holding the largest value of a column, keeping every original column. It tests per-group reductions, tie handling, selecting whole rows after a groupby, and ordering the output with a fresh index.