Encode ordinal severity labels as integers in pandas
Quick Overview
Encode the severity labels low, medium and high as ordinal integers in pandas while keeping the index, the name and an int64 dtype. It tests ordinal encoding with an explicit order, how a failed lookup changes the dtype, and how to handle unexpected labels.
Encode ordinal severity labels as integers in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `encode_ordinal(s: pd.Series) -> pd.Series`. The input is a Series of severity labels, each one of `'low'`, `'medium'` or `'high'`. Return a new Series that replaces each label with its ordinal integer: `'low'` is 0, `'medium'` is 1 and `'high'` is 2.
Requirements:
- The result dtype is `int64` and the result contains no NaN.
- Keep the original index and name.
- Do not mutate the input.
Example:
```python
s = pd.Series(['low', 'high', 'medium'], name='severity')
encode_ordinal(s)
# 0 0
# 1 2
# 2 1
# Name: severity, dtype: int64
```
```hint Check the order and the dtype
Some encoders assign integers in alphabetical order or in order of appearance. Work out what they would give for these three labels, and check what a failed lookup does to the dtype.
```
### What a Strong Answer Covers
- Where the integer order comes from, and why an encoder that infers the order gets it wrong here.
- How the result keeps the index, the name and the `int64` dtype without changing the input.
- What happens to the values and the dtype when a label is missing from the mapping.
- The cost of the lookup.
### Follow-up Questions
- How would you handle an unexpected label that is not in the mapping?
- Some rows have no severity at all. How do you keep an integer dtype?
- How do you make sure training data and serving data use the same encoding?
- When is a 0, 1, 2 encoding a poor choice for a model?
Overview: Encode the severity labels low, medium and high as ordinal integers in pandas while keeping the index, the name and an int64 dtype. It tests ordinal encoding with an explicit order, how a failed lookup changes the dtype, and how to handle unexpected labels.
Implement encode_ordinal(s: pd.Series) -> pd.Series. The input is a Series of severity labels, each one of 'low', 'medium' or 'high'. Return a new Series that replaces each label with its ordinal integer: 'low' is 0, 'medium' is 1 and 'high' is 2.
Requirements:
The result dtype is
int64
and the result contains no NaN.