MCAR Screen: Compare a Metric Across Missing and Present Rows in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `mcar_screen(df, null_col, metric_col)` comparing `metric_col` between rows where `null_col` is null and rows where it is present. Return a `float64` Series named `'mcar_screen'` with exactly this index order: `['n_present', 'n_missing', 'mean_present', 'mean_missing', 'mean_diff', 'std_gap']`. Do not compute a p-value or run a statistical test.
Requirements:
- `n_present` / `n_missing`: row counts where `null_col` is non-NA / NA (rows, not non-null `metric_col` values).
- `mean_present` / `mean_missing`: `metric_col` means per split (NA skipped, the pandas default).
- `mean_diff` = `mean_missing - mean_present`.
- `std_gap` = `mean_diff` / std of `metric_col` over the whole frame (`ddof=1`).
- Every entry, counts included, is `float64`.
- The result is compared with `assert_series_equal`, so the name, index order and dtype must match exactly.
Example:
```python
df = pd.DataFrame({
"income": [50, np.nan, 70, np.nan, 60],
"spend": [10, 30, 20, 40, np.nan],
})
mcar_screen(df, "income", "spend")
```
```text
n_present 3.000000
n_missing 2.000000
mean_present 15.000000
mean_missing 35.000000
mean_diff 20.000000
std_gap 1.549193
Name: mcar_screen, dtype: float64
```
The last row counts as present even though its `spend` is missing, so `n_present` is 3 while `mean_present` averages only 10 and 20. The overall std of `spend` (10, 30, 20, 40 with `ddof=1`) is about 12.91, and 20 / 12.91 is about 1.549.
```hint Two kinds of missing
Decide for each statistic whose missing values it follows: the counts depend only on `null_col`, while the means and the overall std skip missing values of `metric_col`.
```
### What a Strong Answer Covers
- Splitting rows on the nullity of `null_col` and counting rows, including rows where `metric_col` is also missing.
- Split means and an overall `ddof=1` std that skip missing `metric_col` values.
- The exact output contract: name, index order, and `float64` for every entry including the counts.
- What happens when one split is empty or the overall std is zero or undefined.
- What the screen can and cannot say about whether data are missing completely at random.
### Follow-up Questions
- Why is `std_gap` more informative than the raw `mean_diff`?
- If `std_gap` is close to zero, can you conclude that `null_col` is missing completely at random?
- How would you extend this screen into an actual statistical test of MCAR?
Overview: Write a pandas function that splits rows by whether one column is missing and compares another column's mean across the two groups, including a gap scaled by the overall standard deviation. It tests row counting, NaN handling, exact Series output and what a missingness screen can say about MCAR.