💡 Why Data Cleaning Matters in AI
Real-world data is notoriously messy. Sensors fail, web forms leave fields blank, and user entries contain typos. In machine learning and data science, "Garbage In means Garbage Out." If an AI model is trained on datasets containing unhandled missing values (`NaN` or `None`), the model will either throw execution errors or learn skewed patterns. Pandas provides robust tools (`isnull()`, `dropna()`, `fillna()`, `interpolate()`) to sanitize data efficiently.
1. Detecting Missing Values Across a DataFrame (`isnull()`)
Quickly auditing a dataset to locate missing values and calculate exact counts of nulls per column using `.isnull().sum()`.
Python (detect_nulls.py)
import pandas as pd
import numpy as np
def detect_missing_values():
data = {
'Customer': ['Alice', 'Bob', np.nan, 'David', 'Eve'],
'Age': [25, np.nan, 35, 45, np.nan],
'Purchase': [150.5, 200.0, 300.0, np.nan, 410.0]
}
df = pd.DataFrame(data)
print("--- Null Value Count per Column ---")
print(df.isnull().sum())
detect_missing_values()
Output:
--- Null Value Count per Column ---
Customer 1
Age 2
Purchase 1
dtype: int64
2. Dropping Rows with Any Missing Values (`dropna()`)
Dropping every row that contains at least one `NaN` value using `dropna(how='any')`. Useful when data is abundant and purity is critical.
Python (drop_null_rows.py)
import pandas as pd
import numpy as np
def drop_missing_rows():
data = {
'Product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor'],
'Price': [1200.0, np.nan, 75.0, 300.0],
'Stock': [15, 50, np.nan, 10]
}
df = pd.DataFrame(data)
cleaned_df = df.dropna()
print("--- DataFrame After Dropping Rows with NaNs ---")
print(cleaned_df.to_string(index=False))
drop_missing_rows()
Output:
--- DataFrame After Dropping Rows with NaNs ---
Product Price Stock
Laptop 1200.0 15.0
Monitor 300.0 10.0
3. Imputing Numerical Missing Values with Column Mean (`fillna()`)
Filling missing employee salaries with the statistical average (mean) of the existing salaries to preserve dataset size.
Python (impute_mean.py)
import pandas as pd
import numpy as np
def impute_with_mean():
data = {
'Employee': ['John', 'Emma', 'Liam', 'Olivia', 'Noah'],
'Salary': [75000, np.nan, 90000, 82000, np.nan]
}
df = pd.DataFrame(data)
mean_salary = df['Salary'].mean()
df['Salary'] = df['Salary'].fillna(mean_salary)
print(f"Imputed Mean Salary: ${mean_salary:.2f}")
print(df.to_string(index=False))
impute_with_mean()
Output:
Imputed Mean Salary: $82333.33
Employee Salary
John 75000.00
Emma 82333.33
Liam 90000.00
Olivia 82000.00
Noah 82333.33
4. Imputing with Median for Outlier Resistance
Using the median instead of the mean to fill missing property prices, protecting the dataset from extreme high/low outlier distortion.
Python (impute_median.py)
import pandas as pd
import numpy as np
def impute_with_median():
data = {
'Property': ['A', 'B', 'C', 'D', 'E'],
'Price_USD': [250000, np.nan, 275000, 2600000, np.nan] # 2.6M is an outlier
}
df = pd.DataFrame(data)
median_price = df['Price_USD'].median()
df['Price_USD'] = df['Price_USD'].fillna(median_price)
print(f"Median Price Used: ${median_price}")
print(df.to_string(index=False))
impute_with_median()
Output:
Median Price Used: $275000.0
Property Price_USD
A 250000.0
B 275000.0
C 275000.0
D 2600000.0
E 275000.0
5. Custom Imputation Using a Dictionary Map
Filling missing categorical values or specific defaults per column using a Python dictionary passed to `.fillna()`.
Python (dict_fillna.py)
import pandas as pd
import numpy as np
def custom_dict_fill():
data = {
'Item': ['Pen', 'Notebook', 'Eraser', 'Marker'],
'Category': ['Stationery', np.nan, 'Stationery', np.nan],
'Discount_Pct': [0.0, 10.0, np.nan, np.nan]
}
df = pd.DataFrame(data)
fill_values = {'Category': 'General', 'Discount_Pct': 5.0}
df = df.fillna(fill_values)
print("--- Data After Dictionary Imputation ---")
print(df.to_string(index=False))
custom_dict_fill()
Output:
--- Data After Dictionary Imputation ---
Item Category Discount_Pct
Pen Stationery 0.0
Notebook General 10.0
Eraser Stationery 5.0
Marker General 5.0
6. Time-Series Forward Fill (`ffill`) and Backward Fill (`bfill`)
Carrying the last known stock price forward to fill missing weekend or holiday gaps using `.ffill()`.
Python (time_series_fill.py)
import pandas as pd
import numpy as np
def fill_timeseries():
data = {
'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
'Stock_Price': [150.0, np.nan, np.nan, 155.5, 158.0]
}
df = pd.DataFrame(data)
# Forward fill missing values
df['Stock_Price'] = df['Stock_Price'].ffill()
print("--- Stock Prices After Forward Fill ---")
print(df.to_string(index=False))
fill_timeseries()
Output:
--- Stock Prices After Forward Fill ---
Day Stock_Price
Mon 150.0
Tue 150.0
Wed 150.0
Thu 155.5
Fri 158.0
7. Linear Interpolation for Numerical Sensor Data (`interpolate()`)
Estimating missing temperature sensor readings by drawing a straight mathematical line between the preceding and succeeding recorded values.
Python (sensor_interpolate.py)
import pandas as pd
import numpy as np
def interpolate_sensors():
data = {
'Hour': [1, 2, 3, 4, 5],
'Temperature': [20.0, np.nan, np.nan, 26.0, 28.0]
}
df = pd.DataFrame(data)
df['Temperature'] = df['Temperature'].interpolate(method='linear')
print("--- Interpolated Temperature Log ---")
print(df.to_string(index=False))
interpolate_sensors()
Output:
--- Interpolated Temperature Log ---
Hour Temperature
1 20.0
2 22.0
3 24.0
4 26.0
5 28.0
8. Dropping Columns with Excessive Missing Data
Removing entire columns that have more than 50% missing values using the `thresh` parameter in `dropna(axis=1)`.
Python (drop_sparse_columns.py)
import pandas as pd
import numpy as np
def drop_sparse_cols():
data = {
'ID': [1, 2, 3, 4],
'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'Fax': [np.nan, np.nan, np.nan, '555-0192'], # 75% missing
'Notes': [np.nan, np.nan, np.nan, np.nan] # 100% missing
}
df = pd.DataFrame(data)
# Keep columns that have at least 3 non-null values
cleaned_df = df.dropna(axis=1, thresh=3)
print("--- Columns Retained ---")
print(cleaned_df.columns.tolist())
drop_sparse_cols()
Output:
--- Columns Retained ---
['ID', 'Name']
9. Replacing Arbitrary Placeholder Strings with `NaN`
Converting messy strings like `"N/A"`, `"-"`, or `"MISSING"` into proper Pandas `NaN` values using `.replace()`.
Python (replace_placeholders.py)
import pandas as pd
import numpy as np
def clean_placeholders():
data = {
'Customer': ['Alice', 'Bob', 'Charlie', 'David'],
'Score': [85, 'N/A', 90, '-']
}
df = pd.DataFrame(data)
# Replace placeholder strings with NaN
df['Score'] = df['Score'].replace(['N/A', '-'], np.nan)
# Convert column to float & compute mean
df['Score'] = df['Score'].astype(float)
mean_score = df['Score'].mean()
print(f"Computed Valid Score Mean: {mean_score}")
print(df)
clean_clean_placeholders = clean_placeholders()
Output:
Computed Valid Score Mean: 87.5
Customer Score
0 Alice 85.0
1 Bob NaN
2 Charlie 90.0
3 David NaN
10. End-to-End Data Cleaning Pipeline
Combining null detection, placeholder replacement, median imputation, and datatype casting into a single clean pipeline function.
Python (cleaning_pipeline.py)
import pandas as pd
import numpy as np
def run_cleaning_pipeline():
raw_data = {
'OrderID': [101, 102, 103, 104, 105],
'Customer': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Amount': [250.0, 'MISSING', 400.0, np.nan, 150.0],
'Status': ['Completed', 'Pending', 'Completed', 'Completed', 'Cancelled']
}
df = pd.DataFrame(raw_data)
# 1. Replace placeholder text with NaN
df['Amount'] = df['Amount'].replace('MISSING', np.nan).astype(float)
# 2. Impute missing amounts with median
median_amt = df['Amount'].median()
df['Amount'] = df['Amount'].fillna(median_amt)
print("--- Fully Sanitized DataFrame ---")
print(df.to_string(index=False))
run_cleaning_pipeline()
Output:
--- Fully Sanitized DataFrame ---
OrderID Customer Amount Status
101 Alice 250.0 Completed
102 Bob 250.0 Pending
103 Charlie 400.0 Completed
104 David 250.0 Completed
105 Eve 150.0 Cancelled