Missing Rate by Segment
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `missing_by_segment(df, segment_col, value_col)` returning a pandas `Series` with the missing rate of `value_col` within each level of `segment_col`. Each value is the `float64` percentage (0-100 scale) of that segment's rows where `value_col` is NA.
Requirements:
- Index holds the segment values with `index.name` set to `segment_col`.
- Series name is `'pct_missing'`, values are `float64` (compared with `assert_series_equal`).
- Sort by percentage descending, ties broken by segment label ascending.
- Return only the rate Series: do not fill gaps or return rows.
Example:
```python
df = pd.DataFrame({
"segment": ["A", "A", "B", "B", "C", "D", "D"],
"value": [1.0, None, None, 3.0, 4.0, None, None],
})
missing_by_segment(df, "segment", "value")
```
```text
segment
D 100.0
A 50.0
B 50.0
C 0.0
Name: pct_missing, dtype: float64
```
Segment `D` is 100% missing, `A` and `B` tie at 50% so `A` comes first by label, and `C` has no missing values.
```hint Tied rates
Sorting a Series by its values says nothing about the order of equal values. Think about how to put the labels in order first and then keep that order through the value sort.
```
### Constraints & Assumptions
- `segment_col` is guaranteed to contain no NA values.
- The result is compared with `pandas.testing.assert_series_equal`, so the values, index, index name, Series name and dtype must all match.
### What a Strong Answer Covers
- The per-segment share of NA values in `value_col`, scaled to a 0-100 `float64` percentage.
- Segments with no missing values still appear in the result with 0.0.
- A descending sort on the rate with a deterministic ascending-label tie-break.
- The exact Series name, index name and dtype the comparison checks.
### Follow-up Questions
- How would you extend this to report both count and percentage of missing per segment?
- How would you formally test whether missingness depends on the segment?
- A segment is 100% missing. What does that usually tell you about the data, and how does it change your imputation plan?
Overview: Write a pandas function that returns the percentage of missing values in one column for each segment, sorted by rate with a deterministic label tie-break. It tests grouped aggregation on a missingness mask, stable sorting, and matching an exact Series name, index and dtype.