Introduction
Categorical variables are words or labels, not numbers. We need to change them into numbers so computers can understand and learn from them.
from sklearn.preprocessing import OneHotEncoder encoder = OneHotEncoder(sparse_output=False) categorical_data = [['red'], ['green'], ['blue']] encoded_data = encoder.fit_transform(categorical_data)
from sklearn.preprocessing import LabelEncoder le = LabelEncoder() categories = ['cat', 'dog', 'fish'] encoded = le.fit_transform(categories)
from sklearn.preprocessing import OneHotEncoder encoder = OneHotEncoder(sparse_output=False) categories = [['cat'], ['dog'], ['fish']] encoded = encoder.fit_transform(categories)
import pandas as pd df = pd.DataFrame({'color': ['red', 'green', 'blue']}) dummies = pd.get_dummies(df['color'])
from sklearn.preprocessing import OneHotEncoder import numpy as np # Sample categorical data colors = np.array([['red'], ['green'], ['blue'], ['green'], ['red']]) # Create encoder encoder = OneHotEncoder(sparse_output=False) # Fit and transform data encoded_colors = encoder.fit_transform(colors) print('Original data:') print(colors.flatten()) print('\nEncoded data:') print(encoded_colors)
color?get_dummies() to convert categorical columns into one-hot encoded columns.pd.get_dummies(df['color']). Other options are not valid pandas methods.from sklearn.preprocessing import LabelEncoder le = LabelEncoder() df['size_encoded'] = le.fit_transform(df['size']) print(df['size_encoded'].tolist())
df['size'] contains ['small', 'medium', 'large', 'medium'], what will be the printed output?ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). What is the most likely cause and fix?education_level having values: ['high school', 'bachelor', 'master', 'phd']. You want to use this feature in a regression model where order matters. Which encoding method should you choose and why?Pass the test and this pattern moves unknown