one hot encoding

Definizione

One hot encoding is a method used to convert categorical variables into a format that can be provided to machine learning algorithms to improve predictions. It creates binary columns for each category in the original variable, where each column represents the presence (1) or absence (0) of that category.

Esempio

Supponiamo di avere una colonna “Colore” con i seguenti valori: “Rosso”, “Verde”, “Blu”.

Colore
Rosso
Verde
Blu

Dopo aver applicato il one hot encoding, otterremo:

Colore_RossoColore_VerdeColore_Blu
100
010
001

Implementazione in Python

import pandas as pd
from sklearn.preprocessing import OneHotEncoder
 
# Creazione del DataFrame di esempio
data = {'Colore': ['Rosso', 'Verde', 'Blu']}
df = pd.DataFrame(data)
 
# Inizializzazione del OneHotEncoder
encoder = OneHotEncoder(sparse_output=False)
 
# Applicazione del OneHotEncoder
encoded_data = encoder.fit_transform(df[['Colore']])
 
# Creazione di un DataFrame con i dati codificati
encoded_df = pd.DataFrame(encoded_data, columns=encoder.get_feature_names_out(['Colore']))
 
print(encoded_df)

Risorse

OneHotEncoder (scikit-learn)
https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html