Remove punctuation from every string in a pandas Series with a regex
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `def remove_punctuation(s: pd.Series) -> pd.Series` that removes all punctuation (any char that is not a word character or whitespace) from every string using `s.str.replace(r'[^\w\s]', '', regex=True)`.
Requirements:
- Remove any char matching `[^\w\s]`: keep letters, digits, underscore, and whitespace (for example, `'Hello, World!'` becomes `'Hello World'`).
- `NaN` values stay `NaN` (not coerced to a string).
- Preserve the original `index` and `name`.
Example:
```python
s = pd.Series(['Hello, World!', 'a.b-c', "it's $5"])
remove_punctuation(s)
# 0 Hello World
# 1 abc
# 2 its 5
# dtype: object
```
```hint Read the character class
Work out which characters `\w` and `\s` match in Python, then list what the negated class removes besides commas and periods. Try a price, a decimal number and a hyphenated word.
```
### What a Strong Answer Covers
- Exactly what `[^\w\s]` matches, including symbols such as `$` and emoji, and the fact that the underscore survives.
- How `.str.replace` handles missing values and keeps the index and name.
- What deleting characters does to tokens joined by punctuation, such as contractions, hyphenated words, decimals and dates.
- How Unicode affects `\w`: accented letters, combining marks and the regex engine that runs the pattern.
### Follow-up Questions
- How would you collapse the extra whitespace left after removing punctuation?
- How does `\w` behave with Unicode/accented characters?
- When would you replace punctuation with a space instead, or keep characters such as apostrophes and decimal points?
Overview: Write a pandas function that deletes punctuation from every string in a Series with one regex replace, keeping letters, digits, underscores, whitespace, missing values, the index and the name. It tests regex character classes, Unicode word matching and the side effects of deleting characters from text.