Missing Rate Matrix by Segment
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `missing_by_segment_matrix(df, segment_col)` returning a pandas DataFrame with the missing rate of every other column, broken down by the distinct values of `segment_col`.
Requirements:
- Index: distinct values of `segment_col`, including a group for NA segment labels (`dropna=False`), with `index.name` set to `segment_col`.
- Columns: all of `df`'s columns except `segment_col`, in original order.
- Each cell: `float64` percentage (0-100) of that segment's rows where that column is NA per `isna()`.
- Sort index ascending, with the NA segment group last.
- Do not fill or impute anything.
Example:
```python
df = pd.DataFrame({
"vendor": ["alpha", "alpha", "beta", "beta",
"gamma", "gamma", "gamma", "gamma", np.nan, np.nan],
"price": [9.5, 3.0, np.nan, np.nan, 4.0, 5.0, 6.0, 7.0, np.nan, 2.0],
"qty": [1, 2, np.nan, np.nan, 3, np.nan, 5, 6, 7, 8],
})
missing_by_segment_matrix(df, "vendor")
```
```text
price qty
vendor
alpha 0.0 0.0
beta 100.0 100.0
gamma 0.0 25.0
NaN 50.0 0.0
```
Vendor `beta`'s feed died, so both of its columns are 100% missing. One of `gamma`'s four `qty` values is missing (25%), and the two rows with no vendor form their own group, placed last.
```hint Rows without a segment
By default `groupby` drops rows whose key is NA. Check which argument keeps them as a group of their own.
```
```hint All columns at once
Compute missingness for every column in one grouped operation; a loop over columns is not needed.
```
### Constraints & Assumptions
- The grader compares the result with `pandas.testing.assert_frame_equal`: dtypes, ordering and `index.name` must match exactly.
### What a Strong Answer Covers
- Missing rates for every non-segment column as 0-100 `float64` values, with the columns in `df`'s original order.
- A separate group for rows whose segment label is NA, placed after the sorted labels.
- No filling or dropping of data, so a dead feed shows up as 100.0.
- The index name, column order and dtypes that the exact frame comparison checks.
### Follow-up Questions
- How would you flag which (segment, column) cells indicate a likely feed outage?
- How would you extend this to also report each segment's row count?
- How would you turn this matrix into a daily monitor, and what would you compare each day's rates against?
Overview: Write a pandas function that builds a matrix of missing-value percentages for every column, broken down by segment, including a separate group for rows with no segment label. It tests isna masks, groupby with dropna=False, NA-aware index sorting and exact DataFrame matching.