蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行五大清洗策略、pandas 3.1 非链式赋值与防泄露填充实测

PYTHONWindows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。explore-data-cleaning.py
explore-data-cleaning.py259 行
"""Independent offline lab for ML Ch 12: Data Cleaning (missing, outliers, duplicates, inconsistency, CoW & split-safe)."""
import json
import platform

import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split


def make_dirty_customers() -> pd.DataFrame:
    rows = [
        {"customer_id": 101, "age": "28", "city": "shanghai", "gender": "male", "annual_income": 120000.0, "last_spend": 320.0},
        {"customer_id": 102, "age": None, "city": "beijing", "gender": "Female", "annual_income": 135000.0, "last_spend": np.nan},
        {"customer_id": 103, "age": "35", "city": "guangzhou", "gender": "M", "annual_income": 150000.0, "last_spend": 410.0},
        {"customer_id": 104, "age": "42", "city": None, "gender": "F", "annual_income": 145000.0, "last_spend": 260.0},
        {"customer_id": 105, "age": "31", "city": "Beijing", "gender": "男", "annual_income": 128000.0, "last_spend": 190.0},
        {"customer_id": 106, "age": "29", "city": "shanghai", "gender": "female", "annual_income": 140000.0, "last_spend": np.nan},
        {"customer_id": 107, "age": "37", "city": "shenzhen", "gender": "M", "annual_income": 160000.0, "last_spend": 520.0},
        {"customer_id": 108, "age": "45", "city": "beijing", "gender": "女", "annual_income": 155000.0, "last_spend": 380.0},
        {"customer_id": 109, "age": "-5", "city": "shanghai", "gender": "male", "annual_income": 132000.0, "last_spend": 210.0},
        {"customer_id": 110, "age": "300", "city": "guangzhou", "gender": "F", "annual_income": 148000.0, "last_spend": 295.0},
        {"customer_id": 111, "age": "未知", "city": "beijing", "gender": "female", "annual_income": 142000.0, "last_spend": 305.0},
        {"customer_id": 112, "age": "33", "city": "shenzhen", "gender": "M", "annual_income": 1500000.0, "last_spend": 610.0},
        # Two exact duplicate rows of customer 101 and 105
        {"customer_id": 101, "age": "28", "city": "shanghai", "gender": "male", "annual_income": 120000.0, "last_spend": 320.0},
        {"customer_id": 105, "age": "31", "city": "Beijing", "gender": "男", "annual_income": 128000.0, "last_spend": 190.0},
    ]
    return pd.DataFrame(rows)


def main():
    cases = []
    raw_df = make_dirty_customers()

    # 1. Missing values: dropna() vs type-specific non-chained fillna()
    base = raw_df.copy()
    base["age"] = pd.to_numeric(base["age"], errors="coerce")
    missing_before = {k: int(v) for k, v in base.isnull().sum().items()}
    dropped = base.dropna()

    filled = base.copy()
    age_median = float(filled["age"].median())
    city_mode = str(filled["city"].mode().iloc[0])
    filled["age"] = filled["age"].fillna(age_median)
    filled["city"] = filled["city"].fillna(city_mode)
    filled["last_spend"] = filled["last_spend"].fillna(0.0)
    missing_after = int(filled.isnull().sum().sum())

    c1_ok = (
        raw_df.shape == (14, 6)
        and dropped.shape == (10, 6)
        and missing_before["age"] == 2
        and missing_before["city"] == 1
        and missing_before["last_spend"] == 2
        and missing_after == 0
    )
    cases.append(
        dict(
            name="missing_value_drop_and_impute",
            inputs=dict(raw_shape=list(raw_df.shape)),
            prerequisites="构造含空值、非数字字符串与多类型缺失的 14 行客户表(副本操作不改原表)。",
            action="比较 dropna() 整行删除与中位数/众数/0 填充,确认填充后全表缺失数为 0 且原表未受污染。",
            expected=dict(dropped_rows=10, filled_total_missing=0, raw_preserved=True),
            actual=dict(
                dropped_rows=int(dropped.shape[0]),
                filled_total_missing=missing_after,
                raw_preserved=(int(raw_df["city"].isnull().sum()) == 1),
            ),
            measurements=dict(
                missing_before=missing_before,
                age_median_used=age_median,
                city_mode_used=city_mode,
            ),
            passed=c1_ok,
        )
    )

    # 2. Outlier detection via IQR and Z-Score + Winsorization clipping
    inc = filled["annual_income"].copy()
    q1 = float(inc.quantile(0.25))
    q3 = float(inc.quantile(0.75))
    iqr = q3 - q1
    lower_bound = q1 - 1.5 * iqr
    upper_bound = q3 + 1.5 * iqr
    iqr_outliers = inc[(inc < lower_bound) | (inc > upper_bound)].tolist()

    z_scores = (inc - inc.mean()) / inc.std(ddof=1)
    z_outliers = inc[z_scores.abs() > 3.0].tolist()

    clipped = np.where(inc > upper_bound, upper_bound, np.where(inc < lower_bound, lower_bound, inc))
    filled["annual_income"] = clipped
    c2_ok = (
        iqr_outliers == [1500000.0]
        and z_outliers == [1500000.0]
        and float(filled["annual_income"].max()) == upper_bound
        and float(filled["annual_income"].min()) >= lower_bound
        and len(filled) == 14
    )
    cases.append(
        dict(
            name="outlier_iqr_zscore_and_winsorize",
            inputs=dict(iqr_k=1.5, z_threshold=3.0),
            prerequisites="年收入列含 1500000 极端值,其余样本落在 120000-160000。",
            action="分别用 1.5*IQR 与 |Z|>3 检出异常值,并用上下边界做截断(Winsorization)。",
            expected=dict(iqr_outlier_count=1, z_outlier_count=1, clipped_within_bounds=True),
            actual=dict(
                iqr_outlier_count=len(iqr_outliers),
                z_outlier_count=len(z_outliers),
                clipped_within_bounds=(
                    float(filled["annual_income"].max()) <= upper_bound
                    and float(filled["annual_income"].min()) >= lower_bound
                ),
            ),
            measurements=dict(
                q1=q1,
                q3=q3,
                iqr=iqr,
                lower_bound=lower_bound,
                upper_bound=upper_bound,
                max_z_score=round(float(z_scores.abs().max()), 4),
            ),
            passed=c2_ok,
        )
    )

    # 3. Duplicate row detection and deduplication
    dup_count = int(filled.duplicated().sum())
    dedup = filled.drop_duplicates(keep="first").reset_index(drop=True)
    c3_ok = dup_count == 2 and dedup.shape == (12, 6) and int(dedup.duplicated().sum()) == 0
    cases.append(
        dict(
            name="duplicate_detection_and_removal",
            inputs=dict(rows_before=14, keep="first"),
            prerequisites="数据表含 2 条完全重复记录(customer_id 101 与 105)。",
            action="使用 duplicated() 计数并用 drop_duplicates(keep='first') 去重,验证无残余重复行。",
            expected=dict(duplicates_found=2, rows_after=12, remaining_duplicates=0),
            actual=dict(
                duplicates_found=dup_count,
                rows_after=int(dedup.shape[0]),
                remaining_duplicates=int(dedup.duplicated().sum()),
            ),
            measurements=dict(unique_customer_ids=int(dedup["customer_id"].nunique())),
            passed=c3_ok,
        )
    )

    # 4. Inconsistency normalization (text casing, mapping) & erroneous business values
    cleaned = dedup.copy()
    cleaned["city"] = cleaned["city"].str.strip().str.title()
    gender_map = {"male": "男", "female": "女", "Female": "女", "M": "男", "F": "女"}
    # Compare .replace() vs .map(): .replace preserves already-clean '男'/'女', while .map turns them to NaN
    mapped_na_count = int(cleaned["gender"].map(gender_map).isnull().sum())
    cleaned["gender"] = cleaned["gender"].replace(gender_map)

    # Business logic error check on age: valid adult/customer range [0, 120]
    erroneous_mask = (cleaned["age"] < 0) | (cleaned["age"] > 120)
    erroneous_ages = sorted(float(v) for v in cleaned.loc[erroneous_mask, "age"])
    cleaned.loc[erroneous_mask, "age"] = np.nan
    valid_age_median = float(cleaned["age"].median())
    cleaned["age"] = cleaned["age"].fillna(valid_age_median)

    unique_cities = sorted(cleaned["city"].unique().tolist())
    unique_genders = sorted(cleaned["gender"].unique().tolist())
    c4_ok = (
        unique_cities == ["Beijing", "Guangzhou", "Shanghai", "Shenzhen"]
        and unique_genders == ["女", "男"]
        and mapped_na_count == 2
        and erroneous_ages == [-5.0, 300.0]
        and float(cleaned["age"].min()) >= 0.0
        and float(cleaned["age"].max()) <= 120.0
    )
    cases.append(
        dict(
            name="inconsistency_and_erroneous_values",
            inputs=dict(valid_age_range=[0, 120]),
            prerequisites="城市大小写混杂,性别混用中英文缩写,年龄含 -5 与 300 两处业务错误值。",
            action="执行 str.title()、replace() 映射(并对照 map() 会将未映射的已有合法值置空)及业务边界置空重填。",
            expected=dict(
                normalized_cities=4,
                normalized_genders=["女", "男"],
                map_unmapped_to_nan=2,
                erroneous_ages_fixed=True,
            ),
            actual=dict(
                normalized_cities=len(unique_cities),
                normalized_genders=unique_genders,
                map_unmapped_to_nan=mapped_na_count,
                erroneous_ages_fixed=(
                    erroneous_ages == [-5.0, 300.0]
                    and float(cleaned["age"].min()) >= 0.0
                    and float(cleaned["age"].max()) <= 120.0
                ),
            ),
            measurements=dict(
                unique_cities=unique_cities,
                erroneous_ages_found=erroneous_ages,
                valid_age_median=valid_age_median,
                clean_age_min=float(cleaned["age"].min()),
                clean_age_max=float(cleaned["age"].max()),
            ),
            passed=c4_ok,
        )
    )

    # 5. Pandas 3.1 Copy-on-Write safety & split-before-impute anti-leakage check
    cow_demo = pd.DataFrame({"x": [1.0, np.nan, 3.0]})
    cow_demo["x"] = cow_demo["x"].fillna(cow_demo["x"].median())
    cow_safe_ok = int(cow_demo["x"].isnull().sum()) == 0 and float(cow_demo.loc[1, "x"]) == 2.0

    rng = np.random.default_rng(42)
    X_syn = rng.normal(loc=50.0, scale=10.0, size=(100, 2))
    X_syn[[5, 15, 85, 95], 0] = np.nan
    X_syn[90, 0] = 500.0  # extreme value in test region if split without leakage
    y_syn = (X_syn[:, 1] > 50.0).astype(int)
    X_tr, X_te, _, _ = train_test_split(X_syn, y_syn, test_size=0.2, random_state=42)
    imp = SimpleImputer(strategy="median")
    X_tr_imp = imp.fit_transform(X_tr)
    X_te_imp = imp.transform(X_te)
    train_only_med = round(float(imp.statistics_[0]), 4)
    expected_train_med = round(float(np.nanmedian(X_tr[:, 0])), 4)
    c5_ok = (
        cow_safe_ok
        and train_only_med == expected_train_med
        and not np.isnan(X_tr_imp).any()
        and not np.isnan(X_te_imp).any()
    )
    cases.append(
        dict(
            name="pandas3_cow_and_split_safe_imputer",
            inputs=dict(pandas_version=pd.__version__, samples=100, test_size=0.2),
            prerequisites="pandas 3.1 默认启用 Copy-on-Write;监督建模时缺失填充统计量须仅在训练集拟合。",
            action="验证非链式赋值回写 fillna 生效,并核对 SimpleImputer 仅用 X_train 中位数转换 X_test 无数据泄漏。",
            expected=dict(non_chained_fillna_ok=True, imputer_matches_train_median=True, zero_nan_after=True),
            actual=dict(
                non_chained_fillna_ok=cow_safe_ok,
                imputer_matches_train_median=(train_only_med == expected_train_med),
                zero_nan_after=(not np.isnan(X_tr_imp).any() and not np.isnan(X_te_imp).any()),
            ),
            measurements=dict(
                train_median_col0=train_only_med,
                full_data_median_col0=round(float(np.nanmedian(X_syn[:, 0])), 4),
            ),
            passed=c5_ok,
        )
    )

    payload = dict(
        version=platform.python_version(),
        system=platform.system(),
        pandas=pd.__version__,
        cases=cases,
    )
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

入口文件:projects/ml-data-cleaning-lab/explore-data-cleaning.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-data-cleaning.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:机器学习

课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip

下载课程关联工程包:机器学习

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a459.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习