Pandas Tutorial: Data Cleaning Cheat Sheet

In any data science or machine learning workflow, data scientists spend up to 80% of their time on data preparation and cleaning. Raw datasets are notoriously messy, containing missing values, malformed strings, duplicate rows, incorrect data types, and extreme outliers. If unaddressed, these anomalies distort machine learning models and corrupt analytical insights.

Using Pandas in Python, data cleaning becomes systematic and efficient. This comprehensive cheat sheet covers the essential Pandas operations required to transform dirty raw data into clean, analysis-ready datasets.

1. Inspecting Dataframes Before Cleaning

Before modifying a dataset, you must inspect its structural integrity, column data types, and missing value distributions.

C
import pandas as pd
import numpy as np

# Load dataset
df = pd.read_csv('raw_dataset.csv')

# Inspect basic structural information
print(df.info())

# Check summary statistics for numerical columns
print(df.describe())

# Check total missing values per column
print(df.isnull().sum())

# Inspect unique counts for categorical features
print(df['category'].value_counts())

2. Handling Missing Values (NaN)

Missing data can be dropped or imputed depending on the dataset size and distribution.

C
# Drop rows where any column contains NaN
df_dropped = df.dropna()

# Drop columns where all values are missing
df_cleaned_cols = df.dropna(axis=1, how='all')

# Impute missing numerical values with median
df['age'] = df['age'].fillna(df['age'].median())

# Impute missing categorical values with mode or a default label
df['city'] = df['city'].fillna('Unknown')

3. Removing Duplicates and Formatting Strings

Duplicate rows inflate sample sizes, while inconsistent string casing and trailing whitespace break categorical groupings.

C
# Check and remove duplicate rows
print(f"Duplicate count: {df.duplicated().sum()}")
df = df.drop_duplicates().reset_index(drop=True)

# Clean string columns: strip whitespace, lowercase, and remove special characters
df['email'] = df['email'].str.strip().str.lower()
df['product_name'] = df['product_name'].str.replace(r'[^a-zA-Z0-9 ]', '', regex=True)

4. Type Casting and Datetime Conversion

Ensuring columns have correct data types (integers, floats, datetime, categories) optimizes memory and prevents aggregation bugs.

C
# Convert columns to correct data types
df['user_id'] = df['user_id'].astype(int)
df['price'] = pd.to_numeric(df['price'], errors='coerce') # Converts invalid strings to NaN

# Convert date strings into proper Pandas datetime objects
df['order_date'] = pd.to_datetime(df['order_date'], errors='coerce')

# Extract datetime components
df['order_year'] = df['order_date'].dt.year
df['order_month'] = df['order_date'].dt.month

5. Detecting and Handling Outliers (IQR Method)

Extreme outliers can heavily skew statistical metrics and regression models. The Interquartile Range (IQR) method effectively filters out extreme values.

C
# Filter outliers using the Interquartile Range (IQR) method
Q1 = df['salary'].quantile(0.25)
Q3 = df['salary'].quantile(0.75)
IQR = Q3 - Q1

lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR

# Keep only rows within acceptable bounds
df_filtered = df[(df['salary'] >= lower_bound) & (df['salary'] <= upper_bound)]

Conclusion

Mastering data cleaning workflows in Pandas—from inspecting missing values and handling duplicates to casting data types and filtering outliers—ensures your data science and machine learning pipelines train on robust, high-quality data.