One-hot encode a color column in pandas with get_dummies
Quick Overview
Write a pandas function that one-hot encodes a string color column into prefixed boolean dummy columns and drops the original column. It tests get_dummies options, column order, index preservation, and how missing or unseen categories are handled.
One-hot encode a color column in pandas with get_dummies
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `one_hot_colors(df)` that one-hot encodes the string column `'color'` with `pd.get_dummies`, appends the dummy columns, and drops the original `'color'` column.
The function must meet these requirements:
- Prefix `'color'` with the default `'_'` separator (for example `'color_blue'`), one column per distinct value, in `get_dummies` alphabetical order.
- Other original columns (for example `'id'`) stay unchanged and to the left of the dummy columns.
- Dummy columns are `bool` dtype (the default in pandas 2.0 and later).
- Preserve the original row index.
Example:
```python
df = pd.DataFrame({'id': [1, 2, 3], 'color': ['red', 'blue', 'red']})
one_hot_colors(df)
# id color_blue color_red
# 0 1 False True
# 1 2 True False
# 2 3 False True
```
```hint Where the new columns go
Compare what `get_dummies` returns when you pass it a single Series with what it returns when you pass the whole DataFrame and name the columns to encode. One of them already drops the source column and keeps the rest in place.
```
### What a Strong Answer Covers
- Encoding only the `color` column and naming the dummies with the `color_` prefix
- Keeping the other columns unchanged and to the left of the dummies, with the original index
- The dummy dtype and the column order that `get_dummies` produces
- What happens with missing values or a categorical `color` column
### Follow-up Questions
- How would you keep the encoding consistent between training data and new data that contains unseen or missing colors?
- What does `get_dummies` do with `NaN` in the column, and how would you give missing values their own column?
- When would you want integer dummies instead of booleans, and how would you get them?
Overview: Write a pandas function that one-hot encodes a string color column into prefixed boolean dummy columns and drops the original column. It tests get_dummies options, column order, index preservation, and how missing or unseen categories are handled.
Write one_hot_colors(df) that one-hot encodes the string column 'color' with pd.get_dummies, appends the dummy columns, and drops the original 'color' column.
The function must meet these requirements:
Prefix
'color'
with the default
'_'
separator (for example
'color_blue'
), one column per distinct value, in
get_dummies
alphabetical order.
Other original columns (for example
'id'
) stay unchanged and to the left of the dummy columns.
Dummy columns are
bool
dtype (the default in pandas 2.0 and later).