← All Python interview questions
One-hot encode a categorical column for modelling
MediumPandas — CleaningFractalMu Sigma
Before modelling, the plan column has to become numeric dummy columns.
Write encode(df) that returns the DataFrame with plan replaced by one-hot columns named plan_<value>, dropping the first category to avoid collinearity, with the remaining columns as integers (0/1) and the original columns kept.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
users = pd.DataFrame({
"user_id": [1, 2, 3, 4],
"plan": ["basic", "pro", "enterprise", "pro"],
"seats": [1, 5, 40, 8],
})- Step 1: `pd.get_dummies(..., columns=['plan'])` encodes only the column you name and leaves `user_id` and `seats` untouched.
- Step 2: `drop_first=True` removes one category so the dummy columns are not perfectly collinear — important for linear models, unnecessary for trees.
- Step 3: `dtype=int` gives 0/1 integers; the pandas default is boolean, which some estimators and SQL loaders reject.
- Step 4: Categories are ordered alphabetically, so 'basic' is the one dropped and becomes the reference level.
def encode(df):
return pd.get_dummies(df, columns=["plan"], prefix="plan", drop_first=True, dtype=int)Learn the concept first
Stuck on Pandas — Cleaning? These free Python lessons teach it step by step.
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program