数据清洗
系统核对机器学习数据清洗的五大问题类型(缺失、异常、重复、不一致、错误值)及处理流程,并在 pandas 3.1 Copy-on-Write 与防数据泄露约束下实测完整清洗管线。
学完这一章,你能够
- 系统核对机器学习数据清洗的五大问题类型(缺失、异常、重复、不一致、错误值)及处理流程,并在 pandas 3.1 Copy-on-Write 与防数据泄露约束下实测完整清洗管线。
数据清洗的价值与全流程定位
机器学习界常说“垃圾进,垃圾出”(Garbage In, Garbage Out):模型本身无法自动分辨录入噪声与真实规律,原始数据若充斥残缺、重复与极端错误,再强的算法也只会拟合假信号。高质量的数据清洗带来四项直接收益:提升模型预测准确率与泛化表现、保障探索分析与业务结论的可靠性、增强对尺度和噪声敏感算法(如 KNN、SVM)的数值稳定性,以及剔除冗余样本以节约训练算力与耗时。
在机器学习端到端工作流中,数据清洗位于探索理解之后、特征构造与建模之前,且并非一锤子买卖——每当模型验证效果异常时,都需要回溯清洗规则核查是否漏掉隐性脏数据。下表概括了五类最常见的数据质量问题及其应对策略,随后本站使用 pandas、numpy 与 scikit-learn 在自有 14 行合成客户表上逐项实测。
缺失值、异常值与重复值处理
清洗前必须保留原始 DataFrame 的独立副本(df.copy()),切忌直接覆盖源表。针对缺失值,先用 df.isnull().sum() 定位分布,再视缺失比例与业务语义选用删除(dropna)或填充(数值列常用中位数抗偏态、分类列常用众数)。本站对含 14 条记录的合成客户表实测:原始表含 age 缺失 2 处、city 缺失 1 处、last_spend 缺失 2 处(共涉及 4 行,其中 customer_id=102 同行缺失 2 列),执行 dropna() 后剩余 10 行;改用 age 中位数 32.0、city 众数 'shanghai' 与 last_spend 中位数填充后,全表缺失数归零且原始数据保持未修改。
异常值检测最常用两种量化标准:四分位距法(IQR = Q3 - Q1,界外为 [Q1 - 1.5×IQR, Q3 + 1.5×IQR])与 Z-Score 法(通常取 |z| > 3)。识别后既可剔除,也可在确认需要保留样本量时采用缩尾截断(clip/Winsorize)。本站在客户年收入列(含 1 条 1,500,000 极端值)实测:Q1=129,000、Q3=149,500、IQR=20,500、上界 180,250,IQR 与 |z|>3(最大 Z=3.4724)均精确检出该 1 条极端记录,截断后全部数值落在 [98,250, 180,250] 区间内。随后调用 duplicated() 与 drop_duplicates() 检查完全重复记录,实测精准发现并移除 2 条重复行,去重后保留 12 条唯一客户记录。
格式规范化、逻辑错误修正与 pandas 3.1 防泄露实践
文本大小写混杂、前后空格、同义编码(如“男/Male/M”“女/Female/F”)会导致同一类别被拆分成多个孤立分组。对文本字段应先执行 str.strip() 与大小写归一化(如 str.title()),再建立显式映射表统一编码。需注意 pandas Series.map() 遇到未定义键时会返回 NaN(本站实测 2 个未覆盖值转为 NaN,可按需用 fillna 兜底或结合 replace 保留原值)。对于违反常识的逻辑错误(如年龄 -5 岁或 300 岁),必须依据业务有效域(如 [0, 120])先置为 NaN 再用合法样本中位数回填:本站实测标出 [-5.0, 300.0] 并以合法中位数 32.5 回填后,清洁年龄收敛至 [28.0, 45.0],城市归一化为 4 个标准名、性别统一为 ['女', '男']。
工程落地的两条关键准则需要特别纠正与强调:第一,在 pandas 3.x 默认启用的 Copy-on-Write(CoW)机制下,旧教程常见的链式原地写法 df['列'].fillna(val, inplace=True) 不会修改原 DataFrame,必须改为显式赋值 df['列'] = df['列'].fillna(val);第二,进入监督学习阶段后,中位数填充、异常截断阈值等任何依赖样本统计量的清洗器都必须在划分训练/测试集之后仅在训练集 fit,再 transform 测试集,严禁在全表上提前计算统计量造成数据泄露。本站实测 80:20 划分下 SimpleImputer(strategy='median') 严格学习训练集首列中位数 50.3045(而非全表 49.8904),并将训练与测试缺失全部归零。完整项目通常有 60%–80% 时间投入数据探索、备份留痕、业务核对与迭代清洗,这是可靠建模不可绕过的基石。
常见数据质量问题与清洗策略汇总
| 问题类型 | 描述 | 可能的影响 | 常用清洗策略 |
|---|---|---|---|
| 缺失值 | 字段为空(NaN / NULL) | 样本丢失、计算报错或引入估计偏差 | 视比例删除,或按训练集均值/中位数/众数填充 |
| 异常值 | 明显偏离主体分布的极端数值 | 拉偏均值与方差,干扰距离/线性模型 | 用 IQR 或 Z-Score 检出后结合业务删除、截断或修正 |
| 重复值 | 数据表中存在完全相同的冗余记录 | 重复样本权重虚高,污染评估并浪费算力 | 用 duplicated() 定位并 drop_duplicates() 去重 |
| 不一致性 | 大小写、空格、单位或编码口径不统一 | 同一实体被错误拆组,统计与特征失真 | 去空白、统一大小写与显式字典映射规范化 |
| 错误值 | 违背业务常识的非法值(如年龄 -5 或 300) | 误导模型学到荒谬规则 | 按有效域置为缺失后依据业务规则修正或回填 |
运行五大清洗策略、pandas 3.1 非链式赋值与防泄露填充实测
"""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()
- 在自有 14 行客户表与 100 行划分集上核对 dropna 剩 10 行、IQR/Z-Score(3.4724) 检出与截断、去重留 12 条唯一客户、城市/性别归一化与错误年龄 [-5, 300] 修正,以及 SimpleImputer 仅拟合训练集统计量。
所需环境: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。
当前源码 SHA256:3427120ca918458b5ffb599868ab619b72c3dcc76a2c0d796b1b5835e05410e5
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境: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。
ZIP SHA256:d2b7e6fcffdab02f96e4f58af93641741c45f260cda411e3e11defa16e7ca7ca
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在 pandas 3.x 中不建议写 df['年龄'].fillna(median_val, inplace=True),且监督学习里为何不能在划分数据集前用全表中位数填充?
展开参考解答
pandas 3.x 的 Copy-on-Write 会使链式切片的 inplace 修改作用在临时副本上导致原表不变,应改用 df['年龄'] = df['年龄'].fillna(median_val);而在划分前使用全表统计量会把测试集分布信息泄露给训练流程,使评估指标虚高。