Data cleaning
In machine learning, we often hear the saying "garbage in, garbage out," which vividly illustrates the decisive impact of data quality on model performance.
Imagine you are a chef preparing a delicious dish. No matter how skilled you are, if the ingredients are not fresh, contain dirt, or are incomplete, the final dish will inevitably be compromised.
In machine learning,Raw datais our "ingredients", whileData cleaningis the crucial "ingredient preparation" process. It aims to identify, correct, or remove errors, inconsistencies, duplicates, and incomplete parts in the data, preparing clean, high-quality "ingredients" for the subsequent model "cooking".
This article will systematically introduce you to the core concepts and common methods of data cleaning, and through clear code examples, help you master this essential skill for data scientists.
I. Why Is Data Cleaning So Important?
Before diving into technical details, let us first understand why data cleaning is an indispensable part of the machine learning pipeline.
1.1 Improving Model Performance and Accuracy
Dirty data (such as outliers and erroneous values) can mislead the model into learning incorrect patterns. Clean data allows the model to capture the true patterns in the data more accurately, resulting in more reliable predictions.
1.2 Ensuring the Reliability of Analysis Results
Whether it is exploratory data analysis or final business decisions, conclusions drawn from erroneous data are dangerous. Data cleaning ensures a solid and reliable foundation for analysis.
1.3 Improving Algorithm Stability
Many machine learning algorithms are very sensitive to data quality. For example, distance-based algorithms (such as KNN and SVM) are severely affected by outliers, and missing values may render an entire sample unusable.
1.4 Saving Computational Resources and Time
Cleaning out irrelevant and duplicate data can reduce the dataset size, thereby lowering the computational cost and time of model training.
To understand more intuitively where data cleaning fits in the entire machine learning workflow, see the flowchart below:

As can be seen from the figure above, data cleaning is the first step in preprocessing, and when model performance is poor, we often need to return to this step to check and improve data quality.
II. Common Data Problems and Cleaning Strategies
Data cleaning typically addresses the following common types of problems. We can get a quick overview through a simple table:
| Problem Type | Description | Possible Impact | Common Cleaning Strategies |
|---|---|---|---|
| Missing Values | Some fields in a data record have empty values (NaN, NULL). | This causes samples to be discarded, information loss, and calculation errors. | Delete, fill (mean / median / mode / prediction). |
| Outliers | Extreme values that clearly deviate from most of the data. | Distort statistical results and affect model performance. | Identify (IQR, Z-Score), then delete or correct. |
| Duplicate Values | Identical records exist in the dataset. | This causes the model to be overly biased toward duplicate samples, affecting its generalization ability. | Identify and remove duplicates. |
| Inconsistency | Data formats, units, or encodings are inconsistent (e.g., "Nan" meaning male in Chinese, "Male", "M"). | Causes errors in grouping and analysis. | Standardization, normalization, and mapping conversions. |
| Error value | Values that are clearly illogical (e.g., an age of -1 or 300). | Produces meaningless analysis results. | Correct based on business logic or set as missing. |
Next, we will use Python's pandas and numpy library, through concrete code, to demonstrate how to solve these problems.
III. Hands-On Practice: Data Cleaning with Python
Suppose we have a file named customer_data.csv customer dataset, which contains some typical data quality problems.
3.1 Environment Setup and Data Loading
First, ensure you have installed the necessary libraries, then load the data.
Example
Import the necessary libraries
import
pandas
as
pd
import
numpy
as
np
Load the dataset
df
=
pd.
read_csv
(
'customer_data.csv'
)
Please replace with your own file path
View the basic information and first few rows of the data
(
"Dataset shape (rows, columns):"
,
df.
shape
)
(
"\nFirst 5 rows of data:"
)
(
df.
head
(
)
)
(
"\nBasic data information:"
)
(
df.
info
(
)
)
(
"\nStatistical description of the data:"
)
(
df.
describe
(
)
)
3.2 Handling Missing Values
Detecting missing values is the first step.pandas provides convenient methods.
Example
1. Check for missing values
(
"Number of missing values per column:"
)
(
df.
isnull
(
)
.
sum
(
)
)
2. Handling Missing Values - Method 1: Deletion
Delete any row containing missing values (suitable when there are few missing values)
df_dropped
=
df.
dropna
(
)
(
f
"\nAfter dropping missing values, data shape: {df_dropped.shape}"
)
3. Handling Missing Values - Method 2: Filling
A more common method is to fill based on the characteristics of each column
df_filled
=
df.
copy
(
)
For numeric columns (such as 'Age'), fill with the median (more robust to outliers than the mean)
if
'Age'
in
df_filled.
columns
:
df_filled
[
'Age'
]
.
fillna
(
df_filled
[
'Age'
]
.
median
(
)
,
inplace
=
True
)
For categorical columns (such as 'City'), fill with the mode (the most frequently occurring value)
if
'City'
in
df_filled.
columns
:
df_filled
[
'City'
]
.
fillna
(
df_filled
[
'City'
]
.
mode
(
)
[
0
]
,
inplace
=
True
)
For columns that may change over time (such as 'Last Purchase Amount'), filling with 0 sometimes makes more business sense
if
'Last Purchase Amount'
in
df_filled.
columns
:
df_filled
[
'Last Purchase Amount'
]
.
fillna
(
0
,
inplace
=
True
)
(
"\nAfter filling missing values, number of missing values per column:"
)
(
df_filled.
isnull
(
)
.
sum
(
)
)
3.3 Identifying and Handling Outliers
Outlier handling requires caution, as sometimes they represent important special events.
Example
We take 'Annual Income' as an example, assuming it should be a reasonable positive value
if
'Annual Income'
in
df_filled.
columns
:
Method 1: Identify using the Interquartile Range (IQR) method
Q1
=
df_filled
[
'Annual Income'
]
.
quantile
(
0.25
)
Q3
=
df_filled
[
'Annual Income'
]
.
quantile
(
0.75
)
IQR
=
Q3 - Q1
lower_bound
=
Q1 -
1.5
- IQR
upper_bound
=
Q3 +
1.5
- IQR
Find the outliers
outliers
=
df_filled
[
(
df_filled
[
'Annual Income'
]
<
lower_bound
)
|
(
df_filled
['Annual Income'
]
upper_bound
)
]
(
f
"\nNumber of 'Annual Income' outliers found using the IQR method: {len(outliers)}"
)
Handling outliers: here we choose to clip using the upper and lower boundary values (Winsorization)
df_filled
[
'Annual Income'
]
=
np.
where
(
df_filled
[
'Annual Income'
]
upper_bound
,
upper_bound
,
np.
where
(
df_filled
[
'Annual Income'
]
<
lower_bound
,
lower_bound
,
df_filled
['Annual Income'
]
)
)
(
"Outliers in 'Annual Income' have been clipped."
)
3.4 Handling Duplicate Values
Duplicate records increase the computational burden and may introduce bias.
Example
Check for and delete completely duplicate rows
duplicate_rows
=
df_filled.
duplicated
(
)
(
f
"\nNumber of completely duplicate rows found: {duplicate_rows.sum()}"
)
Delete these duplicate rows, keeping only the first occurrence of each record
df_cleaned
=
df_filled.
drop_duplicates
(
)
(
f
"After removing duplicates, data shape: {df_cleaned.shape}"
)
3.5 Handling Inconsistencies
Ensure consistency in data formats and values.
Example
1. Standardize text format: for example, capitalize the first letter in the 'City' column
if
'City'
in
df_cleaned.
columns
:
df_cleaned
[
'City'
]
=
df_cleaned
[
'City'
]
.
str
.
title
(
)
2. Map to unified values: for example, unify gender information to 'Male' and 'Female'
if
'Gender'
in
df_cleaned.
columns
:
gender_mapping
=
{
'male'
:
'male'
,
'female'
:
'female'
,
'M'
:
'male'
,
'F'
:
'female'
}
df_cleaned
[
'Gender'
]
=
df_cleaned
[
'Gender'
]
.
replace
(
gender_mapping
)
You can also use the .map() function, but .replace() is more flexible; unspecified values remain unchanged
3. Convert data types: ensure numeric columns are of a numeric type
if
'Age'
in
df_cleaned.
columns
:
df_cleaned
[
'Age'
]
=
pd.
to_numeric
(
df_cleaned
[
'Age'
]
,
errors
=
'coerce'
)
errors='coerce' converts errors to NaN
After conversion, you can again fill the new NaNs produced by the conversion with the median
df_cleaned
[
'Age'
]
.
fillna
(
df_cleaned
[
'Age'
]
.
median
(
)
,
inplace
=
True
)
(
"\nData cleaning complete! View the first 5 rows of the cleaned data:"
)
(
df_cleaned.
head
(
)
)
IV. Summary and Best Practices
Through the steps above, we have completed a round of basic data cleaning. Remember, data cleaning is not a one-time step but an iterative process. Here are some best practices:
- Explore first, clean later: Before you start cleaning, be sure to use
df.describe()、df.info(), visualization (such as histograms and box plots), and other means to fully understand your data. - Back up the original data: Always keep an original, unmodified copy of the data. All cleaning operations should be performed on the copy.
- Record cleaning steps: Document your cleaning logic (such as why the median was used for filling and how the outlier boundaries were determined). This is crucial for project reproducibility and team collaboration.
- Combine with business logic: Data cleaning is not a purely mathematical operation. For example, "Age=0" is an error in demographic data but may be reasonable in infant product data. Always maintain communication with domain experts.
- Iterate: After cleaning, proceed to the modeling stage. If model performance is poor, go back and check the data quality; you may need to adjust the cleaning strategy.
Data cleaning may occupy a data science project's 60%-80% of its time; although tedious, it is the cornerstone of building powerful, reliable machine learning models.