gpt4 book ai didi

python - 获取 Pandas 的错误消息/异常的值

转载 作者:太空宇宙 更新时间:2023-11-04 11:07:35 25 4
gpt4 key购买 nike

我的 csv 数据框有错误的行。 Pandas 引发带有行号的错误消息。是否有可能获得此号码以用作异常(exception)?

这里是错误信息:

pandas.errors.ParserError: Expected 187 fields in line 55898, saw 188. Error could possibly be due to quotes being ignored when a multi-char delimiter is used.

我想让行 (55898) 将其写入单独的日志文件,然后将其删除。获得“预期”数字 (187) 和“锯”数 (188) 也很好。所以我可以在日志文件中写:

Error at line 55898. Fields added : 1

最佳答案

使用 repr 获取错误字符串并使用 re 修改错误。

import re

try:
<code that raises exception>
except pandas.errors.ParserError as e:
errorstring = repr(e)
matchre = re.compile('Expected (\d+) fields in line (\d+), saw (\d+)')
(expected, line, saw) = map(int, matchre.search(errorstring).groups())
with open('error.log', "a+") as log:
log.write(f'Error at line {line}. Fields added : {saw - expected}.')

关于python - 获取 Pandas 的错误消息/异常的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59073028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com