如何免Series检测pandas DataFrame中的单双引号并按行上报异常?
实现代码
import logging import pandas as pd # 配置日志输出格式,可根据需求调整 logging.basicConfig(level=logging.ERROR, format="%(message)s") # 单元格检测函数:判断是否包含单/双引号 def check_quotes(value): str_val = str(value) return "'" in str_val, '"' in str_val # 全表批量检测,不需要单独操作Series对象 check_result = df.applymap(check_quotes) single_quote_rows = set() double_quote_rows = set() # 遍历检测结果匹配行号 for row_idx, row_content in check_result.iterrows(): for has_single, has_double in row_content: if has_single: single_quote_rows.add(f"R{row_idx + 1}") if has_double: double_quote_rows.add(f"R{row_idx + 1}") # 输出错误日志 if double_quote_rows: logging.error(f"Double quote are detected on {' and '.join(double_quote_rows)}") if single_quote_rows: logging.error(f"Simple quote are detected on {' and '.join(single_quote_rows)}")
补充说明
- 全流程不需要单独操作Series对象,通过全表元素批量映射完成检测,符合你的需求
- 自动将所有单元格转为字符串判断,覆盖数值、字符串等所有类型的单元格检测
- 用set存储命中行号自动去重,同一行多次命中也只会上报一次
- 如果需要中文日志输出,直接修改日志内容即可,示例:
if double_quote_rows: logging.error(f"在 {'、'.join(double_quote_rows)} 行检测到双引号") if single_quote_rows: logging.error(f"在 {'、'.join(single_quote_rows)} 行检测到单引号")
内容的提问来源于stack exchange,提问作者meuhfunk
相关产品推荐
相关产品推荐

