You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python从字符串提取邮箱报错:TypeError: expected string or bytes-like object

解决提取邮箱时的TypeError: expected string or bytes-like object错误

错误原因

你的dfs['from']列里存在非字符串类型的数据(比如NaN、数字或其他非str/bytes对象),re.findall和string.split()无法处理这类输入,因此抛出类型错误。

修复后的函数

修改函数,先对输入做类型校验和预处理,确保只处理字符串:

import re
import numpy as np
import pandas as pd  # 确保导入pandas

def extract_email_ID(input_val):
    # 处理非字符串/空值情况:直接返回NaN
    if pd.isna(input_val) or not isinstance(input_val, str):
        return np.nan
    
    # 优先从<>中提取邮箱
    email = re.findall(r'<(.+?)>', input_val)
    if email:
        return email[0]
    
    # 无<>时,分割字符串筛选含@的内容
    email_list = list(filter(lambda y: '@' in y, input_val.split()))
    return email_list[0] if email_list else np.nan

应用代码

直接将函数传入apply即可,无需额外lambda:

dfs['from'] = dfs['from'].apply(extract_email_ID)

额外优化

  • 提前统一处理列中的非字符串值,提升效率:
    dfs['from'] = dfs['from'].astype(str).replace('nan', np.nan)
    
  • 用更精准的邮箱正则替换简单@判断,减少误匹配:
    # 替换原函数中的re.findall部分
    email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
    email = re.findall(email_pattern, input_val)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:33:13