AI / Machine Learning · 15 November 2026 · 12 min read
Handling Categorical Data in Machine Learning: Encoding with Pandas and Scikit-learn
Learn how to prepare categorical data for machine learning using Binary Encoding and One-Hot Encoding. Explore manual preprocessing with Pandas, Scikit-learn pipelines, and build a complete Logistic Regression classification model using a heart disease dataset.
- Machine Learning
- Data Preprocessing
- Feature Engineering
- Python
- Scikit-learn
- Classification

Handling Categorical Data in Machine Learning: Encoding with Pandas and Scikit-learn
Machine learning models learn patterns from numerical data. But real-world datasets aren't always made up of numbers.
Consider a dataset containing information about patients:
| Age | Sex | ChestPainType | Cholesterol | HeartDisease |
|---|---|---|---|---|
| 40 | M | ATA | 289 | 0 |
| 49 | F | NAP | 180 | 1 |
| 37 | M | ATA | 283 | 0 |
| 48 | F | ASY | 214 | 1 |
Some features contain numerical values, while others contain text labels such as M, F, ATA, and NAP.
A machine learning algorithm cannot directly perform mathematical operations on these text categories in the same way it operates on numerical features.
So, how do we prepare this data before feeding it into a model?
The answer is Categorical Data Encoding.
In this article, we'll understand what encoding is, explore different encoding techniques, implement them manually using Pandas, and then use Scikit-learn to build a complete preprocessing pipeline.
We'll use a real-world dataset to finish with a simple binary classification model using Logistic Regression.
1. What is categorical data?
Categorical data represents information that belongs to a particular group, class, or category.
Unlike numerical data, categorical values usually describe characteristics rather than quantities.
For example:
- Gender: Male, Female
- Chest pain type: ATA, NAP, ASY, TA
- Education: School, Undergraduate, Postgraduate
- Blood group: A, B, AB, O
Categorical features can generally be divided into two major types.
1.1 Binary categorical data
Binary categorical data contains only two possible categories.
Examples:
| Feature | Category 1 | Category 2 |
|---|---|---|
| Sex | Male | Female |
| ExerciseAngina | Yes | No |
| AccountStatus | Active | Inactive |
| IsStudent | Yes | No |
These features can be represented using two numerical values, usually 0 and 1.
1.2 Multi-category data
Multi-category data contains more than two possible categories.
For example, consider the ChestPainType feature:
| Category | Description |
|---|---|
| ATA | Atypical Angina |
| NAP | Non-Anginal Pain |
| ASY | Asymptomatic |
| TA | Typical Angina |
These categories represent different types of chest pain. They do not have a natural numerical ordering.
This distinction is important because the encoding technique we choose depends on the nature of the categorical feature.
2. What is encoding in machine learning?
Encoding is the process of converting categorical values into numerical representations that machine learning algorithms can process.
For example, consider the following feature:
| Sex |
|---|
| Male |
| Female |
| Male |
| Female |
After encoding:
| Sex |
|---|
| 1 |
| 0 |
| 1 |
| 0 |
The model can now process these values as numerical inputs.
However, we should not simply assign arbitrary numbers to every category.
Consider ChestPainType:
- ATA = 1
- NAP = 2
- ASY = 3
- TA = 4
This representation can introduce an artificial ordering into the data. A model might interpret category 4 as numerically greater than category 1, even though these categories have no inherent numerical relationship.
This is why choosing the correct encoding technique matters.
The two techniques we'll focus on are:
- Binary Encoding (0/1 mapping for two-category features).
- One-Hot Encoding (separate binary columns for each category).
3. Types of categorical encoding
3.1 Binary encoding
Binary encoding, in this context, means mapping two possible categories to numerical values, generally 0 and 1.
For example:
| Original Value | Encoded Value |
|---|---|
| Male | 1 |
| Female | 0 |
| Yes | 1 |
| No | 0 |
This technique works well for features that genuinely contain two categories.
Implementation using Pandas:
import pandas as pd
# Example dataset
data = {
'Sex': ['M', 'F', 'M', 'F'],
'ExerciseAngina': ['Y', 'N', 'N', 'Y']
}
df = pd.DataFrame(data)
# Binary encoding
df['Sex'] = df['Sex'].map({
'M': 1,
'F': 0
})
df['ExerciseAngina'] = df['ExerciseAngina'].map({
'Y': 1,
'N': 0
})
print(df)Output:
| Sex | ExerciseAngina |
|---|---|
| 1 | 1 |
| 0 | 0 |
| 1 | 0 |
| 0 | 1 |
The map() function replaces each categorical value according to the dictionary provided.
Important: Always verify the mapped columns for missing values afterward. An unexpected category that isn't present in the mapping dictionary will become NaN.
3.2 One-Hot Encoding
One-Hot Encoding is used when a categorical feature contains more than two possible categories.
Instead of assigning a different integer to every category, it creates a separate binary column for each category.
Let's consider the ChestPainType feature:
Original data:
| ChestPainType |
|---|
| ATA |
| NAP |
| ASY |
| TA |
After One-Hot Encoding:
| ATA | NAP | ASY | TA |
|---|---|---|---|
| 1 | 0 | 0 | 0 |
| 0 | 1 | 0 | 0 |
| 0 | 0 | 1 | 0 |
| 0 | 0 | 0 | 1 |
Each column represents the presence or absence of a particular category.
For example, if a record has ATA, the ATA column gets 1, while the remaining category columns get 0.
Implementation using Pandas:
import pandas as pd
data = {
'ChestPainType': ['ATA', 'NAP', 'ASY', 'TA']
}
df = pd.DataFrame(data)
encoded_df = pd.get_dummies(
df,
columns=['ChestPainType'],
dtype=int
)
print(encoded_df)Pandas provides the get_dummies() function to convert categorical features into dummy or indicator variables.
Documentation: https://pandas.pydata.org/docs/reference/api/pandas.get_dummies.html
4. Understanding the dataset
For practical implementation, we'll use the Heart Failure Prediction dataset available on Kaggle.
Dataset: Heart Failure Prediction Dataset
The dataset contains 918 records and 12 columns, including 11 input features and one target variable.
The objective is to predict whether a patient has heart disease based on the available features.
Dataset features
| Feature | Description | Data Type |
|---|---|---|
| Age | Patient's age | Numerical |
| Sex | M or F | Categorical |
| ChestPainType | Type of chest pain | Categorical |
| RestingBP | Resting blood pressure | Numerical |
| Cholesterol | Serum cholesterol | Numerical |
| FastingBS | Fasting blood sugar indicator | Binary |
| RestingECG | ECG results | Categorical |
| MaxHR | Maximum heart rate | Numerical |
| ExerciseAngina | Y or N | Categorical |
| Oldpeak | ST depression | Numerical |
| ST_Slope | Slope of exercise ST segment | Categorical |
| HeartDisease | Target: 0 or 1 | Binary |
Identifying features for encoding
Based on the dataset, we can categorize the features as follows:
Binary categorical features:
- Sex
- ExerciseAngina
Multi-category features:
- ChestPainType
- RestingECG
- ST_Slope
Already numerical or binary features:
- Age
- RestingBP
- Cholesterol
- FastingBS
- MaxHR
- Oldpeak
FastingBS is already represented using 0 and 1, so it does not require categorical encoding.
5. Loading and exploring the dataset
Download the dataset from Kaggle and extract the CSV file, usually named heart.csv.
Install the required libraries:
pip install pandas numpy scikit-learnLoad the dataset:
import pandas as pd
df = pd.read_csv("heart.csv")
# Display first five records
print(df.head())
# Dataset information
print(df.info())
# Check categorical values
categorical_columns = [
'Sex',
'ChestPainType',
'RestingECG',
'ExerciseAngina',
'ST_Slope'
]
for column in categorical_columns:
print(f"\n{column}:")
print(df[column].unique())Before preprocessing, check for missing values and inspect the target distribution:
print(df.isnull().sum())
print(df['HeartDisease'].value_counts())Understanding the dataset before applying encoding helps identify unexpected values, missing data, and potential data quality issues.
6. Manual categorical data handling using Pandas
Now let's implement the complete encoding process manually.
This approach is useful for understanding how categorical data gets transformed before entering a machine learning algorithm.
First, separate the independent features and target variable.
X = df.drop(columns=['HeartDisease'])
y = df['HeartDisease']Next, split the dataset into training and testing sets.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)Why split first?
Because we should learn preprocessing parameters from training data only. The testing data must remain unseen during the learning process.
Step 1: Binary encoding
We'll use the Pandas map() function.
binary_mapping = {
'Sex': {'M': 1, 'F': 0},
'ExerciseAngina': {'Y': 1, 'N': 0}
}
for column, mapping in binary_mapping.items():
X_train[column] = X_train[column].map(mapping)
X_test[column] = X_test[column].map(mapping)The mapping is predefined, so it can be applied consistently to both datasets.
Step 2: One-Hot Encoding
Now we'll handle features containing multiple categories.
multi_category_features = [
'ChestPainType',
'RestingECG',
'ST_Slope'
]
X_train = pd.get_dummies(
X_train,
columns=multi_category_features,
dtype=int
)
X_test = pd.get_dummies(
X_test,
columns=multi_category_features,
dtype=int
)There is one important issue here.
The training and testing datasets might contain different categories. Consequently, get_dummies() can produce different columns for each dataset.
We need to align them:
X_test = X_test.reindex(
columns=X_train.columns,
fill_value=0
)This ensures that both datasets have the same feature columns in the same order.
An unseen category in the test dataset will have no corresponding training column and therefore be represented by zeros in the aligned columns. This is a limitation to consider when choosing a preprocessing strategy.
Step 3: Scale numerical features
Since we're using Logistic Regression, scaling numerical features is generally beneficial.
from sklearn.preprocessing import StandardScaler
numerical_features = [
'Age',
'RestingBP',
'Cholesterol',
'MaxHR',
'Oldpeak'
]
scaler = StandardScaler()
X_train[numerical_features] = scaler.fit_transform(
X_train[numerical_features]
)
X_test[numerical_features] = scaler.transform(
X_test[numerical_features]
)Notice the difference:
fit_transform()learns scaling parameters from training data and transforms it.transform()applies the same learned parameters to testing data.
We never fit the scaler on testing data.
Step 4: Train the Logistic Regression model
Now the dataset is ready for model training.
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))This completes the manual preprocessing workflow.
Although it works, manually coordinating encoding, column alignment, and scaling can become difficult when the project grows.
That's where Scikit-learn's preprocessing tools become useful.
7. Handling categorical data using Scikit-learn
Scikit-learn provides dedicated preprocessing tools that make the process easier to manage.
The main tools we'll use are:
| Tool | Purpose |
|---|---|
OneHotEncoder |
Converts categorical values into binary columns |
StandardScaler |
Standardizes numerical features |
ColumnTransformer |
Applies different preprocessing to different columns |
Pipeline |
Combines preprocessing and model training |
Step 1: OneHotEncoder
Instead of manually creating columns using Pandas, we can use Scikit-learn's OneHotEncoder.
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(
handle_unknown='ignore'
)
encoded_data = encoder.fit_transform(
df[['ChestPainType']]
)
print(encoded_data.toarray())The encoder learns the available categories and transforms them into binary representations.
The handle_unknown='ignore' parameter allows the encoder to handle categories that weren't encountered during training.
Documentation: https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html
Step 2: ColumnTransformer
Our dataset contains both numerical and categorical features.
We need to apply different preprocessing techniques to different groups of columns.
This is exactly what ColumnTransformer is designed for.
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
numerical_features = [
'Age',
'RestingBP',
'Cholesterol',
'MaxHR',
'Oldpeak'
]
categorical_features = [
'Sex',
'ChestPainType',
'RestingECG',
'ExerciseAngina',
'ST_Slope'
]
binary_features = [
'FastingBS'
]
preprocessor = ColumnTransformer(
transformers=[
(
'num',
StandardScaler(),
numerical_features
),
(
'cat',
OneHotEncoder(handle_unknown='ignore'),
categorical_features
),
(
'bin',
'passthrough',
binary_features
)
]
)Let's understand what's happening:
num: Applies StandardScaler to numerical features.cat: Applies OneHotEncoder to categorical features.bin: Keeps the already numerical binary feature unchanged.
We don't need to manually encode Sex and ExerciseAngina here because OneHotEncoder can handle binary categorical features too.
Step 3: Build a Pipeline
A Pipeline allows us to combine preprocessing and model training into one workflow.
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
model = Pipeline(
steps=[
('preprocessor', preprocessor),
('classifier', LogisticRegression(max_iter=1000))
]
)Our pipeline has two main stages:
- Preprocessing: Encoding categorical data and scaling numerical data.
- Classification: Training the Logistic Regression model.
When we call model.fit(), Scikit-learn automatically fits the preprocessing transformations on the training data before training the classifier.
When we call model.predict(), it applies the already-fitted preprocessing transformations to new data before generating predictions.
This also helps prevent data leakage during cross-validation.
8. Understanding the correct preprocessing workflow
One of the most important concepts in machine learning is preventing data leakage.
Consider a dataset with 1,000 records.
We split it into:
- 800 records for training.
- 200 records for testing.
The correct workflow is:
- Split the original dataset.
- Fit the encoder and scaler using training data.
- Transform training data.
- Transform testing data using the same fitted transformations.
- Train the model.
- Evaluate the model on testing data.
Why is this necessary?
Imagine fitting an encoder or scaler on the complete dataset before splitting it.
The preprocessing stage would have access to information from the testing data. This can make the evaluation less representative of how the model performs on genuinely unseen data.
A Pipeline handles the fitting and transformation sequence consistently.
9. Building a complete binary classification model
Now let's combine everything and train a Logistic Regression classifier.
Our objective is to predict the HeartDisease target:
0: No heart disease.1: Heart disease.
Step 1: Separate features and target
X = df.drop(columns=['HeartDisease'])
y = df['HeartDisease']Step 2: Split the dataset
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)The stratify=y parameter helps maintain the target class proportions in both subsets.
Step 3: Define preprocessing
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
numerical_features = [
'Age',
'RestingBP',
'Cholesterol',
'MaxHR',
'Oldpeak'
]
categorical_features = [
'Sex',
'ChestPainType',
'RestingECG',
'ExerciseAngina',
'ST_Slope'
]
binary_features = ['FastingBS']
preprocessor = ColumnTransformer(
transformers=[
('num', StandardScaler(), numerical_features),
('cat', OneHotEncoder(handle_unknown='ignore'), categorical_features),
('bin', 'passthrough', binary_features)
]
)Step 4: Create the Logistic Regression pipeline
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
model = Pipeline(
steps=[
('preprocessor', preprocessor),
('classifier', LogisticRegression(max_iter=1000))
]
)Step 5: Train the model
model.fit(X_train, y_train)That's it!
The pipeline automatically handles preprocessing and model training.
We don't need to manually encode the training or testing dataset.
Step 6: Generate predictions
y_pred = model.predict(X_test)
print(y_pred)We can also obtain predicted probabilities:
y_prob = model.predict_proba(X_test)
print(y_prob[:5])Each row contains the estimated probabilities for classes 0 and 1.
Step 7: Evaluate the model
Let's evaluate the classifier using multiple metrics.
from sklearn.metrics import (
accuracy_score,
classification_report,
confusion_matrix,
roc_auc_score
)
print("Accuracy:", accuracy_score(y_test, y_pred))
print("\nConfusion Matrix:")
print(confusion_matrix(y_test, y_pred))
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
print(
"ROC-AUC:",
roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
)Understanding the evaluation metrics:
| Metric | Meaning |
|---|---|
| Accuracy | Percentage of correct predictions |
| Precision | How many predicted positive cases are actually positive |
| Recall | How many actual positive cases the model detects |
| F1-score | Harmonic mean of precision and recall |
| ROC-AUC | Measures the model's ability to distinguish between classes |
For a medical classification problem, recall is particularly important because missing a positive case can have serious consequences.
However, precision, recall, calibration, and the costs of false positives and false negatives should all be considered.
Note: This is an educational classification exercise, not a clinically validated diagnostic system. Its predictions should not be used to make medical decisions.
10. Pandas vs Scikit-learn: Which approach should you use?
Both approaches can be useful, depending on the task.
| Criteria | Pandas | Scikit-learn |
|---|---|---|
| Manual data exploration | Excellent | Good |
| Binary mapping | map() |
Custom transformer or mapping |
| One-Hot Encoding | get_dummies() |
OneHotEncoder |
| Numerical scaling | Requires separate handling | StandardScaler |
| Train-test consistency | Requires manual alignment | Built into fitted transformers |
| Cross-validation | More manual work | Pipeline integration |
| Model integration | Manual | Pipeline |
My recommendation is to understand manual encoding first because it helps you understand how categorical data gets converted into numerical features.
For actual machine learning projects, prefer Scikit-learn's ColumnTransformer and Pipeline.
11. Key takeaways
Before feeding categorical data into a machine learning model, remember these points:
- Identify whether a feature is numerical, binary categorical, or multi-category.
- Use binary mapping for two-category features when appropriate.
- Use One-Hot Encoding for nominal categorical features.
- Avoid assigning arbitrary integer values to nominal categories.
- Separate training and testing data before fitting preprocessing transformations.
- Fit encoders and scalers on training data only.
- Use
handle_unknown='ignore'to handle unseen categories. - Use
ColumnTransformerto process different feature groups. - Use
Pipelineto combine preprocessing and model training.
Categorical encoding might seem like a small preprocessing step, but it plays an important role in preparing data for machine learning.
Understanding how and why we transform data is just as important as understanding the algorithm we eventually train.
References
Aditya Manoj Shinde
Author
I'm Aditya, a developer passionate about AI, Machine Learning, and software development. I love exploring new technologies, building projects, and sharing what I learn along the way.