Data Cleaning: Handling Missing Values and Encoding Categorical Features
Introduction to Data Preprocessing
Welcome back to our data exploration journey! In the previous lessons, you learned how to load datasets and perform exploratory data analysis (EDA) to understand the structure and relationships in your data. You identified numerical and categorical features, visualized distributions, and examined correlations. These steps have given you valuable insights into your dataset.
Now that you understand what your data looks like, it's time to prepare it for modeling. This critical step is called data preprocessing, and it addresses common issues that can prevent machine learning algorithms from performing well. In this lesson, we'll focus on three essential preprocessing tasks:
- Splitting your data into training and test sets
- Handling missing values in both numerical and categorical features
- Encoding categorical features into a numerical format that machine learning algorithms can understand
By the end of this lesson, you'll have a complete preprocessing pipeline that prepares your data for the modeling phase we'll tackle in the next unit.
Train-Test Split: Why and How
Before we preprocess our data, it’s best practice to split the data into training and test sets. This split allows us to evaluate our model’s performance on unseen data, simulating how it would perform in the real world. The training set is used to fit the model, while the test set is reserved for final evaluation.
Here’s how you can perform a train-test split using scikit-learn:
After splitting, you should perform all preprocessing steps (imputation, encoding, etc.) using only the training data to compute statistics (like median or mode), and then apply those transformations to both the training and test sets. This ensures that your model evaluation remains unbiased and realistic.
Handling Missing Values in Numerical Features
Missing values are a common problem in real-world datasets. They can occur for various reasons: data entry errors, equipment malfunctions, or simply because the information wasn't available. Whatever the cause, missing values can significantly impact model performance if not handled properly.
Let's first check if our dataset has any missing values:
Example output:
This output shows which columns have missing values and how many are missing in each column of the training set. For numerical features, common strategies include:
- Replacing with the mean (average)
- Replacing with the median (middle value)
- Replacing with the mode (most frequent value)
Median imputation is often preferred over the mean because it's less sensitive to outliers.
