清洗规则详解
修正脏数据,规范化和统一数据
概述
清洗规则用于修正和规范化数据,包括:
- 替换 - 快速修正错误值
- 缺失补全 - 填充空值和缺失
- 规范化 - 统一格式
- 关联补齐 - 通过关联表补全字段
- 去重 - 移除重复记录
替换规则(Replace)
基本替换
{
"type": "replace",
"field": "email",
"search": "example.com",
"replace": "newcompany.com"
}
// user@example.com → user@newcompany.com
使用正则表达式
{
"type": "replace",
"field": "phone",
"search": "^0086",
"replace": "+86",
"regex": true
}
// 0086-13612341234 → +86-13612341234
条件替换(仅替换符合条件的行)
{
"type": "replace",
"field": "status",
"search": "pending",
"replace": "waiting",
"conditions": [
{ "field": "priority", "operator": "greater", "value": 5 }
],
"conditionLogic": "and"
}
// 仅当 priority > 5 时,才将 status 从 pending 替换为 waiting
标准化规则(Normalize)
标准化用于统一数据格式和清理:
数字标准化
{
"type": "normalize",
"field": "salary",
"mode": "number"
}
// "8,000.50" → 8000.5
// "¥5000" → 5000
日期标准化
{
"type": "normalize",
"field": "birth_date",
"mode": "date",
"outputFormat": "YYYY-MM-DD"
}
// "2024/03/23" → "2024-03-23"
// "23-Mar-2024" → "2024-03-23"
提取日期部分
{
"type": "normalize",
"field": "signup_year",
"mode": "date_extract",
"part": "year"
}
// "2024-03-23" → 2024
// "2024年3月23日" → 2024
案例:大小写统一
// 转小写
{
"type": "normalize",
"field": "email",
"mode": "lowercase"
}
// "User@Example.COM" → "user@example.com"
// 转大写
{
"type": "normalize",
"field": "country_code",
"mode": "uppercase"
}
// "us" → "US"
// 首字母大写
{
"type": "normalize",
"field": "name",
"mode": "capitalize"
}
// "john smith" → "John Smith"
移除空白
// 仅移除首尾空白
{
"type": "normalize",
"field": "address",
"mode": "trim"
}
// " 北京市 " → "北京市"
// 移除所有空白
{
"type": "normalize",
"field": "phone",
"mode": "removeAllSpaces"
}
// "130 1234 5678" → "13012345678"
布尔值转换
{
"type": "normalize",
"field": "subscribed",
"mode": "boolean"
}
// "yes" → true
// "no" → false
// "1" → true
// "0" → false
实战示例
例 1:清洗订单数据
[
{ "type": "replace", "field": "email", "search": "\\s+", "replace": "", "regex": true },
{ "type": "normalize", "field": "phone", "mode": "removeAllSpaces" },
{ "type": "normalize", "field": "amount", "mode": "number" },
{ "type": "normalize", "field": "order_date", "mode": "date", "outputFormat": "YYYY-MM-DD" }
]
例 2:员工数据规范化
[
{ "type": "normalize", "field": "email", "mode": "lowercase" },
{ "type": "normalize", "field": "department", "mode": "capitalize" },
{ "type": "replace", "field": "status", "search": "\\s+", "replace": "_", "regex": true }
]
例 3:用户地址标准化
[
{ "type": "normalize", "field": "address", "mode": "trim" },
{ "type": "replace", "field": "address", "search": " +", "replace": " ", "regex": true },
{ "type": "normalize", "field": "country", "mode": "uppercase" }
]
💡 下一步:了解转换规则来统一数据格式。