Menu

Encoding Categorical Data

Encoding Categorical Data

Machine learning models work with numbers, not text, so you must convert categorical data like colours or city names into numerical form before training.

Common encoding methods

  • Label Encoding, which assigns a number to each category.
  • One-hot encoding, which creates separate columns for each category.

Label Encoding

Useful when categories have a natural order, like low, medium, and high.

from sklearn.preprocessing import LabelEncoder

encoder = LabelEncoder()

df["Size"] = encoder.fit_transform(df["Size"])

One-Hot Encoding

Useful when categories have no order, like city names or colors.

df = pd.get_dummies(df, columns=["City"])

get_dummies() creates a new column for each unique category, marking it as 1 or 0 based on presence, which avoids implying any false ranking between categories.

The right encoding method depends on whether your categories have a meaningful order.


Machine Learning Tutorial

AP

Abhishek Pati



Learn via Video Course

Artificial Intelligence and Machine Learning Course Logo

Artificial Intelligence and Machine Learning Course

55 hrs



Get in Touch For Details