Clean a Pandas Currency Series With Median Imputation
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `clean_currency(s)` that turns a Series of messy currency strings (for example `'$1,200.50'`, `'£3,000'`, `'N/A'`, `''`) into a clean `float64` Series with missing values imputed.
Requirements:
- Remove any of `$`, `£`, `,` with a regex `str.replace`.
- Coerce with `pd.to_numeric(errors='coerce')` so junk becomes `NaN`.
- Fill every `NaN` with the single median of the parsed values (`skipna=True`).
- Return `float64` (not object) with the original index intact.
Example:
```python
s = pd.Series(['$1,200.50', '£3,000', 'N/A', ''])
clean_currency(s)
# parsed values: [1200.50, 3000.0, NaN, NaN] -> median of [1200.50, 3000.0] = 2100.25
# 0 1200.50
# 1 3000.00
# 2 2100.25
# 3 2100.25
# dtype: float64
```
```hint Watch the pattern
Check what `$` means in a regular expression, and whether `str.replace` treats your pattern as a regex by default in the pandas version you use.
```
### Constraints & Assumptions
- The input is a pandas Series of strings. Some entries are empty strings or placeholders such as `'N/A'`.
- The only symbols to remove are `$`, `£` and the thousands separator `,`. Other symbols or currencies are out of scope.
- The index can hold any labels, and the output must keep it unchanged.
### What a Strong Answer Covers
- Removing all three symbols in one vectorized `str.replace` call, and why the regex flag and the `$` character need care.
- Why `errors='coerce'` is the right setting for placeholders and empty strings.
- Which values the median is computed over, and why that keeps the junk entries from affecting it.
- How the result is guaranteed to be `float64` with the original index, even when every amount is a whole number.
- What happens when no value parses, and how to notice bad data that coercion quietly turned into `NaN`.
### Follow-up Questions
- What happens if every value fails to parse?
- How would you make imputation group-aware (for example, a median per category)?
- How would you handle negative amounts written in accounting style, such as `'(1,200.00)'`?
- When would you prefer a different fill value, or a flag column marking which rows were imputed?
Overview: Write a pandas function that turns messy dollar and pound strings into a float64 Series and fills values that fail to parse with the median of the rest. It tests regex cleanup with str.replace, pd.to_numeric coercion, median imputation and keeping the original index.