Fill Missing Values in a Nullable Int64 pandas Series Without Changing Its Dtype
Quick Overview
Write a pandas function that replaces every missing entry in a nullable Int64 Series with an integer, keeping the Int64 dtype and the index and leaving the input unchanged. It tests how pandas extension dtypes handle pd.NA and why converting through float can corrupt integer data.
Fill Missing Values in a Nullable Int64 pandas Series Without Changing Its Dtype
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Write `impute_nullable_int(s, fill_value)` that takes a nullable-integer Series (dtype `'Int64'`, missing entries are `pd.NA`) and returns a new Series with every `pd.NA` replaced by the integer `fill_value`.
The result must meet these requirements:
- Result dtype must be `'Int64'` (not `float64`, not `int64`).
- Preserve the original index and element order.
- Return a new Series: do not mutate the input.
For example:
```python
s = pd.Series([1, pd.NA, 3], dtype='Int64')
impute_nullable_int(s, 0)
# 0 1
# 1 0
# 2 3
# dtype: Int64
```
```hint Track the dtype at every step
Write down the dtype after each operation you plan to use. Any step that goes through a NumPy float array turns `pd.NA` into `NaN` and the integers into floats.
```
### Constraints & Assumptions
- `s` has dtype `'Int64'`, and its missing entries are `pd.NA`.
- `fill_value` is a valid Python int within the range `Int64` can represent.
### What a Strong Answer Covers
- Which operation produces the result, and how the dtype stays `Int64` at every step.
- Keeping dtype `Int64`, the original index and the element order, and leaving the input unchanged.
- Why a float round trip breaks the dtype guarantee.
- What the function returns when there are no missing values, only missing values, or no rows.
### Follow-up Questions
- Why does `astype(float)` then `fillna` break the dtype guarantee?
- How would you fill with a per-group value instead of a scalar?
- What should happen if a caller passes `fill_value=2.5`?
Overview: Write a pandas function that replaces every missing entry in a nullable Int64 Series with an integer, keeping the Int64 dtype and the index and leaving the input unchanged. It tests how pandas extension dtypes handle pd.NA and why converting through float can corrupt integer data.
Write impute_nullable_int(s, fill_value) that takes a nullable-integer Series (dtype 'Int64', missing entries are pd.NA) and returns a new Series with every pd.NA replaced by the integer fill_value.
The result must meet these requirements:
Result dtype must be
'Int64'
(not
float64
, not
int64
).