Profile duplicated keys in a pandas DataFrame, including groups with a missing key
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `duplicate_key_profile(df, keys)` that returns a pandas DataFrame with one row per `keys` group that occurs more than once. Groups of size 1 are omitted. Do not de-duplicate `df`.
The output must meet these requirements:
- Columns are the `keys` columns, in the given order, followed by exactly `['n_rows', 'n_extra']`.
- `n_rows` (`int64`) is the number of rows sharing that key, and `n_extra` (`int64`) is `n_rows - 1`.
- Only groups with `n_rows > 1` are included.
- Groups whose key is missing (NA) must still be profiled, as with `groupby(..., dropna=False)`.
- Rows are sorted by `n_rows` descending, then each key column ascending in `keys` order, followed by `reset_index(drop=True)`.
For example, with `keys=['order_id']`:
```python
# order_id: [101, 102, 101, 103, 104, 102, 101, 104, NaN, 105, NaN]
duplicate_key_profile(df, ['order_id'])
# order_id n_rows n_extra
# 0 101.0 3 2
# 1 102.0 2 1
# 2 104.0 2 1
# 3 NaN 2 1
```
```hint Missing keys
Check what `groupby` does by default with rows whose key is missing, and where `sort_values` puts those values.
```
### Constraints & Assumptions
- The grader calls the function with `keys=['order_id']` on a fixed frame that has one key appearing 3 times, two keys appearing twice each, several unique keys, and one NA key appearing twice.
- The result is checked with `assert_frame_equal`, so column order, dtypes and the index must match.
- The function should still work for any list of key columns.
### What a Strong Answer Covers
- Counting rows per key with a grouped size, keeping NA keys with `dropna=False`.
- Filtering to groups with more than one row and deriving `n_extra`.
- A deterministic order: ties on `n_rows` broken by the key columns, with NA keys placed consistently.
- The exact column order, `int64` counts, a clean index, and an input frame left unchanged.
### Follow-up Questions
- How would you extend this to report which non-key columns conflict within each duplicate group?
- The function groups the whole frame in memory. How would you profile duplicate keys on a table too large to fit?
- What does the sum of `n_extra` tell you, and how does it relate to `df.duplicated(subset=keys).sum()`?
Overview: Write a pandas function that lists every key appearing more than once in a DataFrame, with its row count and the number of extra copies, while keeping groups whose key is missing. It tests groupby with dropna, filtering on group size and deterministic multi-key sorting for an exact frame comparison.