Convert a pandas DataFrame column to category dtype without mutating the input
Quick Overview
Write a pandas function that converts a string column to the category dtype and returns a new DataFrame without changing the input. It tests copy semantics, how pandas orders inferred categories, and why categorical columns save memory on repeated values.
Convert a pandas DataFrame column to category dtype without mutating the input
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `to_category(df: pd.DataFrame, col: str) -> pd.DataFrame` that converts the object or string column `col` to the `'category'` dtype via `df[col].astype('category')`. Return a new frame.
The result must meet these requirements:
- Do not mutate the input.
- All other columns and their dtypes stay unchanged.
- The result column is a `CategoricalDtype` with categories `sorted(unique)` and `ordered=False`.
- The result is graded with `assert_frame_equal`, so the dtype and the category order must match exactly.
Example:
```python
df = pd.DataFrame({"city": ["b", "a", "b", "a"], "n": [1, 2, 3, 4]})
out = to_category(df, "city")
out["city"].dtype # CategoricalDtype(categories=['a', 'b'], ordered=False)
out["n"].dtype # int64 (unchanged)
```
```hint Watch the caller's frame
Assigning to a column writes into whichever DataFrame you assign on. Decide which frame that should be before you convert anything.
```
### What a Strong Answer Covers
- How the function leaves the caller's DataFrame untouched
- Why the default conversion yields sorted categories with `ordered=False`, and why the grader cares about category order
- That the index, the column order and the other columns' dtypes are preserved
- What happens to missing values and to a column that is already categorical
### Follow-up Questions
- Why does the `category` dtype save memory for repeated string values?
- How would you make the category order match first-seen order instead of sorted order?
- How are missing values in `col` represented after the conversion?
- When would you set `ordered=True`, and which operations does it enable?
Overview: Write a pandas function that converts a string column to the category dtype and returns a new DataFrame without changing the input. It tests copy semantics, how pandas orders inferred categories, and why categorical columns save memory on repeated values.
Write to_category(df: pd.DataFrame, col: str) -> pd.DataFrame that converts the object or string column col to the 'category' dtype via df[col].astype('category'). Return a new frame.
The result must meet these requirements:
Do not mutate the input.
All other columns and their dtypes stay unchanged.
The result column is a
CategoricalDtype
with categories
sorted(unique)
and
ordered=False
.
The result is graded with
assert_frame_equal
, so the dtype and the category order must match exactly.