Dense-rank points within each team in a pandas DataFrame
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `add_rank_within_group(df)`. The input DataFrame has columns `team` and `points`. Return a copy with a column `rank_in_team` holding the descending dense rank of `points` within each `team` (highest gets `1.0`).
Requirements:
- Rank with `method='dense'`, `ascending=False` (ties share a rank, no gaps).
- `rank_in_team` is `float64`.
- Preserve the original index and row order. Do not mutate the input.
For example:
```python
df = pd.DataFrame({
'team': ['A', 'A', 'A', 'B', 'B'],
'points': [10, 30, 30, 5, 8],
})
add_rank_within_group(df)['rank_in_team'].tolist()
# [2.0, 1.0, 1.0, 2.0, 1.0]
```
```hint Shape of the grouped result
An aggregation gives one row per team. You need one value per original row, on the original index, so check which groupby operations return that shape.
```
### What a Strong Answer Covers
- Ranking inside each team, so the ranks restart at 1 for every team
- Descending dense ranking, with tied points sharing a rank and no gaps
- Attaching the ranks without changing the index or the row order
- Returning a new frame without mutating the input, with `rank_in_team` as `float64`
### Follow-up Questions
- How does `method='dense'` differ from `'min'` and `'first'`?
- Why does `.rank()` on a groupby preserve the original index?
- How would you keep only the rows holding the top two point values in each team, and how would that change if you needed exactly two rows per team?
Overview: Write a pandas function that adds a descending dense rank of points within each team, so ranks restart in every team and tied points share a rank. It tests groupby ranking, how group results align back to the original index and row order, and returning a new frame without mutating the input.