Nullity vs target gap report: rank columns by how missingness shifts the target mean
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Write `nullity_target_gap_report(df, target_col)` that ranks columns by how strongly their nullity shifts the mean of the target. For each column other than `target_col`, split rows into NULL vs PRESENT and compare the mean of `target_col` across the two groups (descriptive only: no p-values, no model).
The function must meet these requirements:
- Return a DataFrame with exactly the columns `['column', 'n_null', 'n_present', 'target_mean_when_null', 'target_mean_when_present', 'gap', 'abs_gap']`.
- `n_null`, `n_present` (`int64`): row counts of the nullity split.
- `gap = target_mean_when_null - target_mean_when_present`, `abs_gap = abs(gap)` (both `float64`).
- Exclude columns with zero missing values or that are entirely missing.
- Sort by `abs_gap` descending, then `column` ascending, then `reset_index(drop=True)`.
```hint Treat nullity as a feature
For each column, `isna()` gives a boolean mask. Use it and its negation to pick the two subsets of the target.
```
```hint Check the dtypes
`assert_frame_equal` compares dtypes. Think about what pandas infers when you build the frame from a list of dicts, and what it infers when no column qualifies at all.
```
### Constraints & Assumptions
- The function is tested on a fixed frame: one column null on high-target rows, one null on low-target rows, one null at random, one never null and one always null.
- The result is compared with `assert_frame_equal`, so column dtypes and column order must match exactly.
### What a Strong Answer Covers
- Building a nullity mask per column, skipping the target column, and computing the target mean on each side of the split.
- Excluding columns that are never null or always null, with a reason why the gap is undefined there.
- Returning exactly the seven required columns with `int64` counts and `float64` means and gaps, including when no column qualifies.
- A deterministic order: `abs_gap` descending, `column` ascending as the tie-break, then an index reset.
- Edge cases such as missing values in the target itself and groups with very few rows.
### Follow-up Questions
- How would you flag a gap as noteworthy without a formal test?
- How would you extend this from a binary or continuous target to a categorical one?
- How would you compute the same report without a Python loop when the frame has thousands of columns?
- If a column's nullity shows a large gap, what does that suggest about how the data is missing, and what would you check next?
Overview: Write a pandas function that splits rows by whether each column is missing, compares the mean of a target column across the two groups, and ranks columns by the size of the gap. It tests nullity masks, group means, exact output dtypes and deterministic sorting during exploratory data analysis.