Skip to content

Intermediate: machine learning · Clustering, dimensionality reduction and feature engineering · topic 40 of 62 · 30 min

Encoding categories and dates

Explanation

Models need numbers, so text categories and dates must be turned into numeric features. One-hot encoding makes a 0/1 column per category. Ordinal encoding numbers categories that have a real order. Dates become useful parts such as month, day of week and "is it a festival week?". This is the heart of feature engineering.

Feature engineering

Feature engineering means creating the inputs a model learns from. A raw order timestamp like "2025-10-25 21:40" is nearly useless to most models. "Saturday", "9 p.m." and "5 days before Diwali" are very useful. Good features often matter more than the choice of algorithm.

One-hot encoding

For a category without order, such as payment method (UPI, Card, COD), make one column per category with 1 if the row has it and 0 otherwise. Why not just number them UPI = 1, Card = 2, COD = 3? Because a model would think COD is "more" than UPI and that Card is halfway between, which is meaningless.

paymentpay_Cardpay_CODpay_UPI
UPI001
COD010
Card100
python
import pandas as pd
from sklearn.preprocessing import OneHotEncoder

pd.get_dummies(df["payment"], prefix="pay")                  # quick, in pandas
enc = OneHotEncoder(handle_unknown="ignore").fit(X_train[["payment"]])   # safe in pipelines
handle_unknown="ignore" stops the model from crashing when a new category (like "Wallet") appears after deployment. Shown only.

Ordinal encoding

When categories have a real order, such as education level (10th < 12th < Graduate < Postgraduate) or T-shirt size (S < M < L), map them to ordered numbers. Tree models can also handle plain ordinal codes for unordered categories reasonably well, but linear models and k-NN cannot.

Many categories

A pin-code column has thousands of values; one-hot would create thousands of mostly-zero columns. Options: group rare categories into "Other", use frequency encoding (replace each category by how often it appears), or target encoding (replace it by the average target for that category). Target encoding is powerful but leaks the answer unless it is computed on training folds only; libraries do this with cross-fitting.

Dates and times

  • Parts: year, month, day of month, day of week (Monday = 0 in Python's weekday()), hour.
  • Flags: is_weekend, is_month_end (salary days change spending), is_holiday or "days to Diwali".
  • Differences: account age in days, days since last order.
  • Cyclical features: hour 23 is next to hour 0; some models benefit from sine and cosine encodings of hour and month.
python
from datetime import date

d = date.fromisoformat("2025-10-25")
print(d.year, d.month, d.weekday(), d.weekday() >= 5)
Shows 2025 10 5 True: 25 October 2025 is a Saturday (weekday 5).

Text and other raw columns

Simple numeric features can be pulled from text: length of a review, number of exclamation marks, whether an address contains a flat number. Module 10 goes much further with text.

Common mistakes

  • Label-encoding unordered categories for a linear model. Fix: one-hot.
  • Building the category list from all data, then crashing on new categories in production. Fix: fit on training data with handle_unknown="ignore".
  • Target encoding computed on the whole dataset. Fix: compute it inside training folds.
  • Keeping the raw date string as a category. Fix: extract parts and differences.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Encoding categories and dates · 1/6

Feature engineering

Models need numbers. Feature engineering turns raw columns into useful numbers.

Prefer a video by a teacher? Find free videos on “feature engineering one hot encoding date features machine learning” on YouTube ↗

In real life: Food-delivery demand features

To forecast orders per area per hour, a team engineers features: hour of day, day of week, is_weekend, is_payday (1st–5th of the month), rain in the last hour, days to the next big festival, and the cuisine mix of open restaurants (one-hot). The raw timestamp alone gave a weak model; these engineered features cut the forecast error by a large margin.

Practice (0/3 done)

Task 1 · Code · Python

Write one_hot(values) that returns (categories, rows): categories is the sorted list of distinct values, and rows has one list per value with 1 in the position of its category and 0 elsewhere.

Task 2 · Code · Python

Write date_features(text) for a date like "2025-10-25". Return a dict with "year", "month", "weekday" (Monday = 0 … Sunday = 6), "is_weekend" (True for Saturday or Sunday) and "is_payday" (True when the day of the month is 1 to 5). Use datetime.date.fromisoformat.

Task 3 · Code · Python

Write frequency_encode(values) that replaces each value with the share of rows that have the same value, rounded to 4 decimal places (useful for columns with many categories, like pin codes).

Quick quiz

Question 1

1.Why is one-hot better than UPI = 1, Card = 2, COD = 3 for a linear model?

Question 2

2.Which column is a good fit for ordinal encoding?

Question 3

3.A new payment method "Wallet" appears after deployment. What prevents a crash?

Question 4

4.What is the risk of target encoding computed on the full dataset?

Question 5

5.In Python, date(2025, 10, 25).weekday() is 5. Which day is it?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Why is one-hot better than UPI = 1, Card = 2, COD = 3 for a linear model?

Answer: It does not invent a false order or distance between categories

Numbers imply order and size; one-hot does not.

Which column is a good fit for ordinal encoding?

Answer: Education level: 10th, 12th, Graduate, Postgraduate

It has a natural order.

A new payment method "Wallet" appears after deployment. What prevents a crash?

Answer: An encoder fitted with handle_unknown="ignore"

Unknown categories become all zeros instead of an error.

What is the risk of target encoding computed on the full dataset?

Answer: Leakage: each row's own target influences its feature

Compute it within training folds.

In Python, date(2025, 10, 25).weekday() is 5. Which day is it?

Answer: Saturday

weekday() counts Monday as 0, so 5 is Saturday.

You write to a US client. Which date is clearest?Related

Answer: 4 May 2026

Writing the month as a word avoids confusion between Indian and US date order.

From Days, months and dates

Why group months by strftime('%Y-%m', order_date) rather than by month names like "Mar 2025"?Related

Answer: 'YYYY-MM' text sorts in time order; month names sort alphabetically

Format month names only for display, after sorting.

From Writing reports with aggregation

To get each customer's product categories in SHOP, which tables must the query pass through?Related

Answer: customers, orders, order_items and products

Keys connect customers → orders → order_items → products; you cannot skip a link.

From Joining three or more tables

Why are dates stored as 'YYYY-MM-DD' text in SQLite?Related

Answer: Because the date functions understand it and it sorts correctly as text

Year first and fixed widths make text order equal to date order.

From Working with dates

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Clustering, dimensionality reduction and feature engineering” before its exam: Scaling and transforming numbers, Feature selection, leakage and pipelines.
  2. Module 8 exam: Clustering, dimensionality reduction and feature engineering · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Neural networks and deep learning. 62 topics left in the course before the final exam.

← Previous: Other clustering methods and dimensionality reduction