Encoding and Imputation

Python · Machine Learning (Scikit-Learn)

Theory

Models need numbers with no gaps, but real tables contain text categories and missing values. OneHotEncoder turns a category column into one 0/1 column per value: city with Jaipur, Pune and Delhi becomes city_Delhi, city_Jaipur and city_Pune, with a single 1 in each row. handle_unknown='ignore' makes a city never seen in training encode as all zeros instead of raising an error. OrdinalEncoder maps ordered categories such as S < M < L to 0, 1, 2 when the order is meaningful.

SimpleImputer fills missing values with a statistic learned from the training data: strategy='mean' or 'median' for numbers, 'most_frequent' for categories, or 'constant' with fill_value. Like scalers, encoders and imputers learn in fit, so fit them on training data only. add_indicator=True also adds a column flagging which values were missing, which can itself be useful.

Why we use it

Almost every real dataset has text columns and gaps, and scikit-learn models reject both. Encoders and imputers convert them consistently, so the same mapping is applied to training data, test data and future predictions.

When to use it

Use OneHotEncoder for unordered categories with a manageable number of values, OrdinalEncoder for ordered ones or for tree models. Use the median for skewed numbers and most_frequent for categories. For many columns, combine them with ColumnTransformer.

How it works

  1. Raw columns with text and gaps
  2. Are there missing values? Yes: SimpleImputer with mean/median/most_frequent. No: Continue.
  3. Is the column categorical? Yes: Encode it. No: Leave numbers as they are (or scale).
  4. Do categories have a natural order? Yes: OrdinalEncoder. No: OneHotEncoder(handle_unknown='ignore').
  5. Fit on train, transform train and test
  6. All-numeric, gap-free feature matrix

Syntax

from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder
from sklearn.impute import SimpleImputer
OneHotEncoder(handle_unknown='ignore', sparse_output=False)
OrdinalEncoder(categories=[['S', 'M', 'L']])
SimpleImputer(strategy='median')

Example

ohe = OneHotEncoder(handle_unknown='ignore', sparse_output=False)
X_city = ohe.fit_transform(df[['city']])
print(ohe.get_feature_names_out())

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic