Overview
Provides a complete, reusable pandas data cleaning pipeline for raw datasets. Covers missing value strategies (drop, fill, interpolate), duplicate detection and removal, dtype inference and safe casting, string normalization, outlier detection (IQR, Z-score, isolation forest), column renaming conventions, and a full end-to-end cleaning function template that can be dropped into notebooks or scripts.
When to Use This Skill
- Receiving raw data from exports, APIs, or databases that needs preparation.
- Exploratory data analysis (EDA) before modeling.
- Building reproducible data preparation steps for ML or reporting.
Prerequisites
- Python environment with pandas, numpy, and optionally scikit-learn for advanced outlier detection.
- The raw dataset (CSV, Parquet, DataFrame in memory, or SQL query result).
- Understanding of the domain (what "valid" looks like for each column).
Steps
Initial inspection:
df.head(), df.info(), df.describe(include='all'), df.isnull().sum().
- Identify obvious issues (mixed types, weird strings, extreme values).
Missing values strategy (per column or group):
- Drop rows/columns if <5% missing and not critical.
- Fill with median/mean/mode for numeric.
- Forward/backward fill or interpolate for time series.
- "Unknown" or sentinel value for categorical.
- Flag rows with missing critical fields.
Duplicates:
- Exact duplicates:
drop_duplicates().
- Fuzzy duplicates (same entity different spelling): use
recordlinkage or simple key normalization + group.
Dtype cleaning & casting:
- Infer dtypes safely.
- Convert dates with
pd.to_datetime(errors='coerce').
- Numeric with
pd.to_numeric(errors='coerce').
- Categorical for low-cardinality strings.
String normalization:
.str.strip().str.lower().
- Remove accents, normalize unicode.
- Standardize categories (map "USA", "U.S.", "United States" → "US").
Outlier detection & treatment:
- IQR method for most numeric.
- Z-score for near-normal distributions.
- Domain-specific rules (negative age, price > 10x median, etc.).
- Cap, clip, or flag rather than blindly remove.
Column hygiene:
- Rename to snake_case, consistent naming.
- Reorder columns logically.
- Add derived columns (e.g.,
is_weekend, age_group).
Validation:
- Assert expected columns, dtypes, row count range, no nulls in critical fields.
- Great Expectations or custom checks.
Output:
- Reusable
clean_data(df: pd.DataFrame) -> pd.DataFrame function.
- Before/after summary statistics.
- Notebook cells or script that can be run on new files.
- Export to Parquet/CSV with metadata.
Examples
A complete cleaning pipeline for a typical customer/orders dataset (handle missing emails, normalize country codes, detect price outliers, deduplicate on customer_id + email, cast dates, add features) with before/after reports is included.
Edge Cases & Error Handling
- Mixed types in a column: Coerce and report how many rows became NaN.
- Very large files: Use
chunksize or Dask / Polars for out-of-core.
- Time series specific: Resample, forward fill with limits, detect gaps.
Verification
- Run the cleaner on the raw data — no errors.
clean_df.isnull().sum() shows only expected missing values.
clean_df.dtypes are correct.
- Spot checks: random samples look reasonable.
- Row count and key statistics are within expected ranges (or documented changes are explained).
- Re-run on a new batch of raw data produces consistent output shape.
- Success: The cleaned dataset is ready for analysis or modeling with documented transformations.
References
1---2name: pandas-data-cleaner3description: Cleans, transforms, and validates datasets using pandas. Use when preparing raw data for analysis, modeling, or export.4license: Apache-2.05---67## Overview89Provides a complete, reusable pandas data cleaning pipeline for raw datasets. Covers missing value strategies (drop, fill, interpolate), duplicate detection and removal, dtype inference and safe casting, string normalization, outlier detection (IQR, Z-score, isolation forest), column renaming conventions, and a full end-to-end cleaning function template that can be dropped into notebooks or scripts.1011## When to Use This Skill1213- Receiving raw data from exports, APIs, or databases that needs preparation.14- Exploratory data analysis (EDA) before modeling.15- Building reproducible data preparation steps for ML or reporting.1617## Prerequisites1819- Python environment with pandas, numpy, and optionally scikit-learn for advanced outlier detection.20- The raw dataset (CSV, Parquet, DataFrame in memory, or SQL query result).21- Understanding of the domain (what "valid" looks like for each column).2223## Steps24251. **Initial inspection**:26 - `df.head()`, `df.info()`, `df.describe(include='all')`, `df.isnull().sum()`.27 - Identify obvious issues (mixed types, weird strings, extreme values).28292. **Missing values strategy** (per column or group):30 - Drop rows/columns if <5% missing and not critical.31 - Fill with median/mean/mode for numeric.32 - Forward/backward fill or interpolate for time series.33 - "Unknown" or sentinel value for categorical.34 - Flag rows with missing critical fields.35363. **Duplicates**:37 - Exact duplicates: `drop_duplicates()`.38 - Fuzzy duplicates (same entity different spelling): use `recordlinkage` or simple key normalization + group.39404. **Dtype cleaning & casting**:41 - Infer dtypes safely.42 - Convert dates with `pd.to_datetime(errors='coerce')`.43 - Numeric with `pd.to_numeric(errors='coerce')`.44 - Categorical for low-cardinality strings.45465. **String normalization**:47 - `.str.strip().str.lower()`.48 - Remove accents, normalize unicode.49 - Standardize categories (map "USA", "U.S.", "United States" → "US").50516. **Outlier detection & treatment**:52 - IQR method for most numeric.53 - Z-score for near-normal distributions.54 - Domain-specific rules (negative age, price > 10x median, etc.).55 - Cap, clip, or flag rather than blindly remove.56577. **Column hygiene**:58 - Rename to snake_case, consistent naming.59 - Reorder columns logically.60 - Add derived columns (e.g., `is_weekend`, `age_group`).61628. **Validation**:63 - Assert expected columns, dtypes, row count range, no nulls in critical fields.64 - Great Expectations or custom checks.65669. **Output**:67 - Reusable `clean_data(df: pd.DataFrame) -> pd.DataFrame` function.68 - Before/after summary statistics.69 - Notebook cells or script that can be run on new files.70 - Export to Parquet/CSV with metadata.7172## Examples7374A complete cleaning pipeline for a typical customer/orders dataset (handle missing emails, normalize country codes, detect price outliers, deduplicate on customer_id + email, cast dates, add features) with before/after reports is included.7576## Edge Cases & Error Handling7778- **Mixed types in a column**: Coerce and report how many rows became NaN.79- **Very large files**: Use `chunksize` or Dask / Polars for out-of-core.80- **Time series specific**: Resample, forward fill with limits, detect gaps.8182## Verification83841. Run the cleaner on the raw data — no errors.852. `clean_df.isnull().sum()` shows only expected missing values.863. `clean_df.dtypes` are correct.874. Spot checks: random samples look reasonable.885. Row count and key statistics are within expected ranges (or documented changes are explained).896. Re-run on a new batch of raw data produces consistent output shape.907. Success: The cleaned dataset is ready for analysis or modeling with documented transformations.9192## References9394- [Pandas User Guide - Working with missing data](https://pandas.pydata.org/docs/user_guide/missing_data.html)95- [Pandas Best Practices](https://pandas.pydata.org/docs/development/best_practices.html)96- [Data Cleaning with Python (book)](https://www.oreilly.com/library/view/data-cleaning-with/9781492056447/)