Detect Rare Categorical Levels Below a Share Threshold in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `rare_levels(s: pd.Series, threshold: float = 0.05) -> pd.Series` that returns the levels whose share of non-null values is below `threshold`, with each one's share. Return only the rare levels, not a transformed column.
The result must follow these rules:
- The proportion is computed over non-null values (NaN is excluded from the counts and the denominator) and is a `float64` fraction in [0, 1], not a percentage.
- A level is included only when its proportion is strictly less than `threshold`.
- The result is a Series named `proportion`, indexed by level, with index name `level`.
- Rows are sorted by proportion ascending, then by level ascending.
- If no level is rare, return an empty Series with the same name and index name and dtype `float64`.
For example:
```python
s = pd.Series(["a", "a", "a", "a", "a", "a", "b", "b", "c", "d"])
rare_levels(s, threshold=0.15)
```
```text
level
c 0.1
d 0.1
Name: proportion, dtype: float64
```
`a` has a share of 0.6 and `b` has 0.2, both at or above 0.15, so only `c` and `d` are returned. They tie at 0.1 and are ordered by level.
A second example, with a missing value:
```python
s = pd.Series(["x", "x", "x", None, "y"])
rare_levels(s, threshold=0.22)
```
```text
Series([], Name: proportion, dtype: float64)
```
There are 4 non-null values, so `y` has a share of 0.25 and nothing falls below 0.22. Counting the missing value in the denominator would give `y` a share of 0.2 and flag it by mistake.
```hint Ordering with ties
Sorting by the proportions alone leaves the order of tied levels up to the sort algorithm. Think about how to make the level a secondary key on a Series.
```
### Clarifying Questions to Ask
- Can `s` be a Categorical with unused categories, and should those count as rare with a share of 0?
- Can the levels be of mixed types, such as integers and strings, which would make sorting by level ambiguous?
### What a Strong Answer Covers
- Computing shares over non-null values only.
- Applying a strict comparison against the threshold.
- Producing a deterministic order, with proportion first and level as the tie-breaker.
- Setting the Series name, index name and `float64` dtype, including in the empty case.
### Follow-up Questions
- How would you extend this to return the `count` alongside the proportion?
- What if the analyst wants rare levels grouped into a single `'Rare'` bucket?
- How would you choose the threshold for a model feature, and which data should the rare levels be computed on?
Overview: Implement a pandas function that finds the levels of a categorical Series whose share of non-null values falls below a threshold and returns each share. It tests value_counts normalization, null handling, strict thresholds, deterministic tie-breaking and exact Series metadata.