Cómo tratar variables categóricas

Ingeniería de características para Machine Learning en Python

Robert O'Callaghan

Director of Data Science, Ordergroove

Codificación de variables categóricas

Ingeniería de características para Machine Learning en Python

Codificación de variables categóricas

Ingeniería de características para Machine Learning en Python

Codificación de variables categóricas

  • One-hot encoding
  • Codificación dummy
Ingeniería de características para Machine Learning en Python

One-hot encoding

pd.get_dummies(df, columns=['Country'], 
               prefix='C')
    C_France    C_India    C_UK    C_USA
0          0          1       0        0
1          0          0       0        1
2          0          0       1        0
3          0          0       1        0
4          1          0       0        0
Ingeniería de características para Machine Learning en Python

Codificación dummy

pd.get_dummies(df, columns=['Country'],
               drop_first=True, prefix='C')
     C_India    C_UK    C_USA
0          1       0        0
1          0       0        1
2          0       1        0
3          0       1        0
4          0       0        0
Ingeniería de características para Machine Learning en Python

One-hot vs. dummies

  • One-hot encoding: variables explicables
  • Codificación dummy: información necesaria sin duplicar
Ingeniería de características para Machine Learning en Python
Índice Sexo
0 Masculino
1 Femenino
2 Masculino
Índice Masculino Femenino
0 1 0
1 0 1
2 1 0
Índice Masculino
0 1
1 0
2 1
Ingeniería de características para Machine Learning en Python

Limitar tus columnas

counts = df['Country'].value_counts()
print(counts)
'USA'      8
'UK'       6
'India'    2
'France'   1
Name: Country, dtype: object
Ingeniería de características para Machine Learning en Python

Limitar tus columnas

mask = df['Country'].isin(counts[counts < 5].index)

df['Country'][mask] = 'Other'
print(pd.value_counts(colors))
'USA'      8
'UK'       6
'Other'    3
Name: Country, dtype: object
Ingeniería de características para Machine Learning en Python

Ahora ya tratas variables categóricas

Ingeniería de características para Machine Learning en Python

Preparing Video For Download...