Sub topic 2
Quick Encoding with `pandas.get_dummies`
Assume you know basic pandas DataFrames, NumPy arrays, and training/test splits. A categorical feature stores labels such as "red" or "green" rather than measured numbers. Most machine learning models need numeric feature matrices.
One-hot encoding with pandas
One-hot encoding creates one binary column for each category. A row contains 1 in the column matching its category and 0 elsewhere.
import pandas as pd
df = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
encoded = pd.get_dummies(df, columns=["color"], dtype=int)
print(encoded)The result contains color_blue, color_green, and color_red. The original color column is removed.
Using scikit-learn's `OneHotEncoder`
OneHotEncoder is useful when preprocessing belongs inside a model workflow. It separates learning the categories from converting rows:
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["green", "purple"]})
encoder = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
encoder.fit(train)
print(encoder.get_feature_names_out())
print(encoder.transform(test))The encoder learns categories during fit. transform then uses that learned mapping.
Fit on training data, transform everywhere
Fit preprocessing only on training data. Fitting on the test set leaks information about future data into the training process. It can also produce different columns for different datasets.
flowchart TD
A[Training categories] --> B[Fit encoder]
B --> C[Transform training data]
B --> D[Transform test or production data]Handling unseen categories
handle_unknown="ignore" converts an unseen category into zeros across the learned category columns. In the example, "purple" does not create a new feature and does not raise an error.
Inspect generated names when debugging:
print(encoder.get_feature_names_out())Exercise
Why should an encoder be fitted on training data only?
Show answer
Fitting on training data prevents test-set information from influencing the learned category mapping and keeps feature columns consistent.