Categorical Encoding
One-Hot Encode Small
Create one binary column per category. For each row, the column for its
category is 1 and all other columns are 0. By hand, build a per-category
indicator list with a nested loop. With pandas, pd.get_dummies() does the
same in one call — cast to int for 0/1 output since pandas returns bool by
default.
By hand
With pandas
pd.get_dummies(df['c']) returns a DataFrame with one boolean column per
category, in sorted alphabetical order. Chain .astype(int) to convert
True/False to 1/0 — pandas 2.x returns bool by default. The
snapshot shows dtype: int64 after the cast and the per-column indicator
lists.
naive.py
labels = ['cat', 'dog', 'bird', 'cat']
cats = sorted(set(labels))
result = {}
for c in cats:
result[c] = []
for s in labels:
for c in cats:
result[c].append(1 if s == c else 0)
print('RESULT:', result)
library.py
import pandas as pd
from dalib.display import set_display
set_display()
labels = ['cat', 'dog', 'bird', 'cat']
df = pd.DataFrame({'c': labels})
ohe = pd.get_dummies(df['c']).astype(int)
result = {c: ohe[c].tolist() for c in ohe.columns}
print('columns:', ohe.columns.tolist())
print('dtype:', ohe.dtypes[0])
print('RESULT:', result)
columns: ['bird', 'cat', 'dog']
dtype: int64
RESULT: {'bird': [0, 0, 1, 0], 'cat': [1, 0, 0, 1], 'dog': [0, 1, 0, 0]}
Implementation notes
pd.get_dummies()sorts columns alphabetically — the same order assorted(set(labels))in the naive half, so RESULT columns align.- The default dtype in pandas 2.x is
bool. Add.astype(int)when downstream code expects 0/1 integers rather than True/False. - One-hot creates k columns for k categories;
label-encode(this chapter) creates a single integer column — both represent the same information but one-hot avoids implying ordinal ranking. - Cross-reference:
label-encode(this chapter) for the integer-code alternative.