Convert float account codes to zero-padded 5-character strings in pandas
Quick Overview
Write a pandas function that turns a float64 Series of integer account codes into zero-padded 5-character strings, keeping the index and name and returning object dtype. It tests casting order, string padding without truncation, and how pandas versions store string results.
Convert float account codes to zero-padded 5-character strings in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `codes_to_padded_str(s)`. The input is a `float64` Series of integer account codes (for example `5.0`). Return each code as a zero-padded 5-character string (for example `'00005'`).
```python
import pandas as pd
def codes_to_padded_str(s: pd.Series) -> pd.Series:
...
```
For example:
```python
s = pd.Series([5.0, 42.0, 7.0], name="acct")
codes_to_padded_str(s)
# 0 00005
# 1 00042
# 2 00007
# Name: acct, dtype: object
```
Each code loses its `.0`, gets left-padded with zeros to five characters, and keeps its index label and the Series name.
```hint Watch the float
Look at what `str(5.0)` produces before you pad anything.
```
### Constraints & Assumptions
- All values are non-negative and integer-valued, and there are no `NaN` values to handle.
- Cast to `int64` before formatting so no `'.0'` leaks into the output.
- Left-pad with `zfill(5)`. Codes with 5 or more digits are not truncated.
- Return `object` dtype holding Python `str`.
- Preserve the original `index` and `name`.
### What a Strong Answer Covers
- Why the cast to an integer type has to happen before the string conversion.
- Padding without truncating codes that are already 5 or more digits long.
- Getting `object` dtype in the result regardless of how the pandas version stores strings by default.
- Keeping the index and name, and the cost of a vectorized chain compared with `apply`.
### Follow-up Questions
- How would you handle a Series that does contain `NaN`?
- Why prefer a vectorized `.astype(int).astype(str).str.zfill(5)` over `apply`?
- What happens if a value is not integer-valued, such as `5.7`, and how would you catch it?
Overview: Write a pandas function that turns a float64 Series of integer account codes into zero-padded 5-character strings, keeping the index and name and returning object dtype. It tests casting order, string padding without truncation, and how pandas versions store string results.
Implement codes_to_padded_str(s). The input is a float64 Series of integer account codes (for example 5.0). Return each code as a zero-padded 5-character string (for example '00005').
import pandas as pd
def codes_to_padded_str(s: pd.Series) -> pd.Series:
...