使用Pandas .apply()结合正则函数时遇TypeError问题求助
问题原因分析
你遇到的TypeError: expected string or bytes-like object报错,本质是因为虽然你的列类型标记为object,但列中存在非字符串类型的元素(比如NaN、None,或者不小心混入的数值类型)。re.match()只能处理字符串/字节对象,遇到这些非字符串值时就会抛出错误——哪怕单个字符串测试没问题,批量处理时只要有一个非字符串值就会触发报错。
解决方案:两种处理思路
思路1:修改自定义函数,添加类型检查与异常处理
给你的get_total_time_minutes函数加上输入类型判断,同时处理正则匹配失败的情况(比如格式不符合要求的字符串),返回NaN作为默认值:
import re import numpy as np import pandas as pd SEARCH_PATTERN = r'([0-9]{1,2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})' def get_total_time_minutes(time_col, pattern=SEARCH_PATTERN): """Uses regex to parse time_col which is a string in the format 'd hh:mm:ss' to obtain a total time in minutes """ # 先判断输入是否为有效字符串 if not isinstance(time_col, str): return np.nan # 尝试匹配正则,处理匹配失败的情况 match_result = re.match(pattern, time_col) if not match_result: return np.nan # 计算总分钟数 days, hours, minutes, _ = match_result.groups() return (int(days)*24 + int(hours))*60 + int(minutes) # 现在执行apply就不会报错了 df['Minutes Available'] = df['Resource available (d hh:mm:ss)'].apply(get_total_time_minutes)
思路2:使用Pandas向量化操作(更高效)
apply是逐行处理,大数据量下效率较低。推荐用str.extract直接提取时间组件,再向量化计算总分钟数,这种方法会自动忽略非字符串/格式不匹配的行,返回NaN:
# 提取时间的四个部分,转为数值类型 time_components = df['Resource available (d hh:mm:ss)'].str.extract(SEARCH_PATTERN).astype(float) # 计算总分钟数:(天数*24 + 小时)*60 + 分钟 df['Minutes Available'] = (time_components[0] * 24 + time_components[1]) * 60 + time_components[2]
额外排查步骤
如果想确认列里到底有哪些非字符串元素,可以运行以下代码查看:
# 查看列中各数据类型的数量 print(df['Resource available (d hh:mm:ss)'].apply(type).value_counts()) # 筛选出非字符串的行 non_string_rows = df[~df['Resource available (d hh:mm:ss)'].apply(lambda x: isinstance(x, str))] print(non_string_rows)
这样你就能针对性地清理这些异常数据(比如填充默认值、删除无效行)。
内容的提问来源于stack exchange,提问作者Sam Ezebunandu
相关产品推荐
相关产品推荐

