Group-Wise Mode Imputation in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `fill_group_mode(df)` for a pandas DataFrame with a group column `'dept'` and a string column `'title'` that contains missing values. Replace each NaN in `'title'` with the mode of `'title'` within that row's `'dept'` and return a new DataFrame.
The result must:
- Have the same shape, columns, and index as the input.
- Keep `'title'` as `object` dtype.
- Leave the input `df` unmodified.
You may assume each department's non-null titles have a single mode (no ties).
For example:
```python
df = pd.DataFrame({
'dept': ['A', 'A', 'A', 'B', 'B'],
'title': ['eng', 'eng', None, 'pm', None],
})
fill_group_mode(df)['title'].tolist()
# ['eng', 'eng', 'eng', 'pm', 'pm']
```
```hint Keep the result aligned
Use a grouped operation whose output has the same index as the input, so the filled column can be assigned straight back.
```
```hint Most frequent value
pandas has a Series method that returns the most frequent values while skipping missing entries. Check what it returns when a group has no observed values at all.
```
### What a Strong Answer Covers
- Finding each department's most frequent non-null title, with missing values excluded from the count.
- Filling only the missing titles while keeping the result aligned to the original index, shape and columns.
- Working on a copy so the input is not mutated, and keeping `'title'` as `object` dtype.
- What the code does for a department with no observed titles, and how ties would be broken without the no-ties guarantee.
- The cost of running a Python function once per group, and a vectorized alternative when there are many groups.
### Follow-up Questions
- How would you handle departments where every `'title'` value is NaN?
- How would you break ties deterministically if a department had more than one mode?
- With millions of rows and many departments, how would you avoid calling a Python function once per group?
Overview: Write a pandas function that fills missing string values with the most frequent value in each row's department, returning a new frame with the same index and dtype. It tests groupby with transform, mode computation, handling groups with no observed values, and deterministic tie-breaking.