Normalize Sentinel Tokens to NaN
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `normalize_sentinels(df: pd.DataFrame) -> pd.DataFrame`. Replace every exact occurrence of the sentinel tokens `''`, `'NA'`, `'?'` and `'unknown'` with `np.nan` across the whole frame.
Requirements:
- Matching is case-sensitive and must equal the full cell value, so `'Unknown'`, `' NA '` and `'NAME'` stay as they are.
- Do it with a single frame-wide pandas call; do not loop over the cells in Python.
- Return a new DataFrame with the same shape, columns and index.
- Do not mutate `df`.
Example:
```python
df = pd.DataFrame({'name': ['Ann', 'NA', ''], 'city': ['?', 'Rome', 'unknown']})
out = normalize_sentinels(df)
# name city
# 0 Ann NaN
# 1 NaN Rome
# 2 NaN NaN
```
```hint Whole values only
Make sure the method you pick compares whole cell values. Some ways of matching text look for the token anywhere inside the string, so a cell such as `'NANCY'` would count as a hit for `'NA'`.
```
### Constraints & Assumptions
- The frame can mix text columns and numeric columns. Only string cells can equal one of the tokens.
### What a Strong Answer Covers
- A single frame-wide replacement of the four tokens with `NaN`
- How the method guarantees exact, case-sensitive, full-value matching
- Why the input frame is left unchanged and the shape, columns and index are kept
- What happens to numeric columns, and to column dtypes after the replacement
- How the approach compares with calling a Python function on every cell
### Follow-up Questions
- How would you strip whitespace so that `' NA '` is also treated as a sentinel?
- Why is a vectorized replacement preferable to applying a Python function to every cell?
- How would you handle these tokens when loading the data from a CSV file?
- What if a token is a real value in one column, such as `'NA'` as a country code, but a missing-value marker in another?
Overview: Write a pandas function that replaces exact sentinel strings such as empty strings, NA, ? and unknown with NaN across a whole DataFrame without mutating it. It tests exact versus substring matching, regex pitfalls, and how to handle missing-value markers when loading a CSV.