Return the integer codes of a pandas categorical Series as int8
Quick Overview
Write a pandas function that returns the integer codes of a categorical Series as an int8 Series, with missing values as -1 and the original index kept. It tests how categoricals store their data, how codes follow category order, and when a narrow integer cast overflows.
Return the integer codes of a pandas categorical Series as int8
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `category_codes(s: pd.Series) -> pd.Series` that returns the integer codes of a category-dtype Series as an `int8` Series. Each code indexes into the categories array.
The result must meet these requirements:
- The values are the category codes, with dtype `int8`.
- Missing values map to `-1`.
- Preserve the input index.
- The result name must be `None`, even when the input Series has a name.
Example:
```python
s = pd.Series(['b', 'a', None, 'b'], dtype='category')
# categories: ['a', 'b']
category_codes(s)
# 0 1
# 1 0
# 2 -1
# 3 1
# dtype: int8
```
```hint What a categorical stores
A category-dtype Series already keeps one integer per row internally. Find the accessor that exposes those integers, then check which dtype pandas gives them.
```
### What a Strong Answer Covers
- Where the codes come from and how each one maps back to `s.cat.categories`.
- How missing values are represented.
- Why the index survives and the name ends up as `None`.
- When the `int8` cast is safe and what happens when it is not.
### Follow-up Questions
- How do the codes relate to the category ordering?
- Why cast to `int8`, and when would that break?
- How would you turn a Series of codes back into labels?
Overview: Write a pandas function that returns the integer codes of a categorical Series as an int8 Series, with missing values as -1 and the original index kept. It tests how categoricals store their data, how codes follow category order, and when a narrow integer cast overflows.
Implement category_codes(s: pd.Series) -> pd.Series that returns the integer codes of a category-dtype Series as an int8 Series. Each code indexes into the categories array.
The result must meet these requirements:
The values are the category codes, with dtype
int8
.
Missing values map to
-1
.
Preserve the input index.
The result name must be
None
, even when the input Series has a name.