Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Master Data Science with Python

Lesson 45 of 60 · python

Encoding Categorical Variables for Machine Learning

Duration: 15 minutes

Encoding Categorical Variables

Machine learning models require numeric input, so we must convert categorical variables.

One‑Hot Encoding (low cardinality)

df_onehot = pd.get_dummies(df, columns=['city', 'gender'], drop_first=True)

Label Encoding with scikit‑learn

from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df['dept_code'] = le.fit_transform(df['department'])

Frequency Encoding

freq = df['category'].value_counts() / len(df)
df['category_freq'] = df['category'].map(freq)

Target Encoding (mean encoding) – risk of leakage

target_means = df.groupby('city')['target'].mean()
df['city_target_enc'] = df['city'].map(target_means)

Choosing the right encoder

CardinalityRecommended Encoder
< 10One‑Hot
10‑100Frequency / Target
> 100Hashing or Embedding

Info

Never fit encoders on the test set – fit on training data only and apply to the test set.

Previous: Feature Scaling: Normalization and StandardizationNext: Introduction to Machine Learning with Scikit‑learn