Replace -999 Sentinel Values With NaN in a pandas DataFrame
Quick Overview
Write a pandas function that turns a -999 placeholder into real missing values in every column of a DataFrame without changing the input. It tests why sentinels distort summary statistics, how the replacement changes column dtypes, and how to handle sentinels that differ by column or appear at read time.
Replace -999 Sentinel Values With NaN in a pandas DataFrame
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `sentinel_to_nan(df)` that replaces every `-999` (in any column) with `np.nan` and returns a new DataFrame.
```python
import numpy as np
import pandas as pd
def sentinel_to_nan(df: pd.DataFrame) -> pd.DataFrame:
...
```
Requirements:
- Replace the sentinel across all columns.
- Return a new DataFrame: do not mutate `df`.
- Preserve shape, column names and index.
- Columns that gain a `NaN` become `float64`.
Example:
```python
df = pd.DataFrame({"age": [30, -999, 45], "income": [-999, 50000, 60000]})
sentinel_to_nan(df)
# age income
# 0 30.0 NaN
# 1 NaN 50000.0
# 2 45.0 60000.0
```
```hint Swap a value everywhere
pandas has a DataFrame method that swaps one value for another in every column and returns a new frame by default. Once you have it, think about what the swap does to an integer column's dtype.
```
### What a Strong Answer Covers
- Why pandas does not treat `-999` as missing and what that does to summary statistics
- How the replacement reaches every column without mutating the input
- What happens to the dtype of a column that gains a `NaN`
- Which stored values match the sentinel and which do not, such as `-999.0` or the string `'-999'`
### Follow-up Questions
- What if different columns use different sentinels (for example `-999` and `"N/A"`)?
- How would you handle the sentinel when the data is first read from a CSV file?
- How would you keep integer columns as integers after the sentinel becomes missing?
- How would you check a new dataset for sentinels nobody told you about?
Overview: Write a pandas function that turns a -999 placeholder into real missing values in every column of a DataFrame without changing the input. It tests why sentinels distort summary statistics, how the replacement changes column dtypes, and how to handle sentinels that differ by column or appear at read time.