Machine Learning with scikit-learn

One Hot Encoding in Python with pandas and scikit-learn

Turn text categories into 0/1 columns, and keep the same columns for new data with OneHotEncoder.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • pd.get_dummies for quick encoding
  • OneHotEncoder with fit and transform
  • handle_unknown="ignore" for new categories
city -> [Lima, Paris, Tokyo]
Paris
0
1
0
Tokyo
0
0
1
Oslo
0
0
0

One column per category

Découvrez One Hot Encoding in Python (pandas and scikit-learn) avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  1. pd.get_dummies builds the columns from the values it finds, so train and test can get different columns.
  2. OneHotEncoder learns the categories with fit and always produces the same columns with transform.
  3. handle_unknown="ignore" turns an unseen category (Oslo) into all zeros instead of an error.
  4. sparse_output=False returns a normal array instead of a sparse matrix.

Quand l’utiliser ?

  • Train and evaluate classic machine learning models on tabular data.
  • Prepare features: split, scale and encode data the way real projects do.
  • Compare models fairly with cross-validation and the right metric.

Code d’exemple

main.py
import pandas as pd
from sklearn.preprocessing import OneHotEncoder

train = pd.DataFrame({"city": ["Paris", "Tokyo", "Lima", "Tokyo"], "size": [3, 1, 2, 2]})
test = pd.DataFrame({"city": ["Lima", "Oslo"], "size": [1, 3]})

# pandas: quick, but the columns depend on which values appear
print(pd.get_dummies(train, columns=["city"], dtype=int))
print(list(pd.get_dummies(test, columns=["city"], dtype=int).columns))

# scikit-learn: learns the categories once and reuses them
encoder = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
encoder.fit(train[["city"]])
print(encoder.get_feature_names_out().tolist())
print(encoder.transform(test[["city"]]).astype(int).tolist())  # Oslo is unknown -> all zeros
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

size  city_Lima  city_Paris  city_Tokyo
0     3          0           1           0
1     1          0           0           1
2     2          1           0           0
3     2          0           0           1
['size', 'city_Lima', 'city_Oslo']
['city_Lima', 'city_Paris', 'city_Tokyo']
[[1, 0, 0], [0, 0, 0]]

Explication du code

Cet exemple montre One Hot Encoding in Python (pandas and scikit-learn) en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

S'entraîner avec un défi

Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.

Tous les défis

Outils pour cette leçon