Back to Practice
#0077
One-Hot Encode a Categorical Column
MediumML20 min20 XP
Problem
Given a list of category strings, return a list of dictionaries. Each dictionary should contain one key per sorted category in the form prefix_category, with 1 for the row category and 0 otherwise.
Why This Matters
Most ML models need numeric inputs. One-hot encoding is the first categorical encoding every beginner should understand deeply.
Function Signature
def one_hot(values, prefix):
Examples
Example 1
Inputvalues = ["red", "blue", "red"], prefix = "color"
Output[{"color_blue":0,"color_red":1}, {"color_blue":1,"color_red":0}, {"color_blue":0,"color_red":1}]
Each category becomes its own binary feature.
Constraints
- Sort categories alphabetically.
- Return one dictionary per input value.
- Values are strings.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Two categories
Input["red", "blue", "red"], "color"
Expectedthree encoded rows
Sorted categories create color_blue then color_red.
Hidden Test Categories
single categoryempty inputthree categories