Coerce a pandas Series of strings to nullable Int64, turning invalid entries into NA
Quick Overview
Write a pandas function that converts a Series of integer-looking strings with empty or invalid entries into the nullable Int64 dtype, keeping the index and name. It tests numeric coercion, pandas missing-value markers and the edge cases that break a direct integer cast.
Coerce a pandas Series of strings to nullable Int64, turning invalid entries into NA
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
You are given an object `Series` of integer-looking strings mixed with invalid entries such as empty strings and non-numeric text. Implement `def coerce_to_nullable_int(s: pd.Series) -> pd.Series` so that valid entries parse to integers and bad entries become missing.
The function must meet these requirements:
- Return dtype `Int64` (the nullable extension type).
- Unparseable positions hold `pd.NA`, not `np.nan`.
- Preserve the original `index` and `name`.
Example:
```python
s = pd.Series(['5', '', 'x', '12'])
coerce_to_nullable_int(s)
# 0 5
# 1 <NA>
# 2 <NA>
# 3 12
# dtype: Int64
```
```hint Two steps
Separate the job into getting every entry to a number or a missing value, and then choosing the dtype.
```
```hint The intermediate dtype
Check which dtype pandas gives a numeric Series that contains missing values, and why that is not `Int64`.
```
### What a Strong Answer Covers
- Turning every unparseable entry into a missing value without raising.
- Reaching the nullable `Int64` dtype with `pd.NA` at the bad positions, and what the intermediate dtype is along the way.
- Keeping the original index and name, with no dropped or reordered rows.
- Inputs outside the happy path, such as float-looking strings and very large integers.
### Follow-up Questions
- What happens to float-looking values like `'5.7'`, and how would you handle them?
- Why prefer `Int64` over the default float coercion?
- The column holds 18-digit account IDs. What can go wrong with this approach, and what would you do instead?
- How would you report how many entries failed to parse, and which raw values they were?
Overview: Write a pandas function that converts a Series of integer-looking strings with empty or invalid entries into the nullable Int64 dtype, keeping the index and name. It tests numeric coercion, pandas missing-value markers and the edge cases that break a direct integer cast.
You are given an object Series of integer-looking strings mixed with invalid entries such as empty strings and non-numeric text. Implement def coerce_to_nullable_int(s: pd.Series) -> pd.Series so that valid entries parse to integers and bad entries become missing.