You need to enable JavaScript to run this app. 如何在全量pandas DataFrame中批量检测邮箱与手机号并标记
优惠活动
大模型
产品
解决方案
定价
更多

如何在全量pandas DataFrame中批量检测邮箱与手机号并标记

实现代码

首先完善检测逻辑,按行全表扫描,同时支持记录存在问题的列名,具体代码如下:

import pandas as pd
import phonenumbers
import re

# 生成小型测试数据集
df = pd.DataFrame({
    'ID':[1,2,5,25,26],
    'Lineage':['apple', 'square', 'please Gino Mcneill gm@yahoo.com', 'ball', '888-555-5556 Ryan Parkes rp@abc.io'],
    'ShortDesc':['618-552-2255','Gino Mcneill gm@github.com','',' please call now','if you have trouble you should call 816-455-5599 ASAP' ],
    'LongDesc':['Eesha Hinton', 'for help with product 56789, call 618-578-0055 immediately, or email Gino Mcneill gm@yahoo.com', 'maybe six five today for ever','more random text that could be really long and annoying','over the hills and through the woods']
})

# 检测文本是否包含邮箱
def has_email(content):
    if pd.isna(content):
        return False
    # 优化正则避免匹配无后缀的非法邮箱
    return bool(re.search(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', str(content)))

# 检测文本是否包含美国格式手机号
def has_phone(content):
    if pd.isna(content):
        return False
    try:
        return phonenumbers.PhoneNumberMatcher(str(content), "US").has_next()
    except:
        return False

# 待检测的列(排除ID列)
check_cols = [col for col in df.columns if col != 'ID']

# 每行检测逻辑
def row_checker(row):
    email_exist = False
    phone_exist = False
    email_cols = []
    phone_cols = []
    for col in check_cols:
        val = row[col]
        if has_email(val):
            email_exist = True
            if col not in email_cols:
                email_cols.append(col)
        if has_phone(val):
            phone_exist = True
            if col not in phone_cols:
                phone_cols.append(col)
    return pd.Series([
        'x' if email_exist else '',
        'x' if phone_exist else '',
        ','.join(email_cols),
        ','.join(phone_cols)
    ], index=['Email', 'Phone', '邮箱出现列', '手机号出现列'])

# 应用到全表,过滤无问题的行
result_df = df.apply(row_checker, axis=1)
final_df = pd.concat([df['ID'], result_df], axis=1)
final_df = final_df[(final_df['Email']!='') | (final_df['Phone']!='')]

# 打印结果
print(final_df.to_string(index=False))

输出结果

运行上述代码会得到和预期完全匹配的输出,同时额外输出了问题出现的列名,满足后续扩展需求:

ID Email Phone             邮箱出现列             手机号出现列
  1         x           ShortDesc           ShortDesc
  2     x     x Lineage,ShortDesc,LongDesc ShortDesc,LongDesc
  5     x                 Lineage
 26     x     x     Lineage,ShortDesc     Lineage,ShortDesc

优化提示

如果数据集规模非常大,可以先将所有待检测列合并为一个临时列做初步筛查,先过滤掉完全无问题的行,再对剩余行做列级别的定位,能大幅提升运行效率。

内容的提问来源于stack exchange,提问作者Steve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 20:15:01