当处理原始数据时,出现下面的错误:
id,name,date
0,a,2020/01/01
0,b,2020/01/01
0,c,2020/01/01
0,d,2020/01/01
0,e,2020/01/01
0,f,9999/01/01
用pandas进行处理:
data = pandas.read_csv(file, sep=";", encoding="ISO-8859-1", parse_dates=["date"], date_parser=lambda x: pandas.to_datetime(x, format="%d.%m.%Y"))
但是运行时报错,意思是out of bonds timestamp。
我们目前的做法是,需要跳过异常的行,
需要添加下面的行
date_parser=lambda x: pd.to_datetime(x, errors="coerce")
errors参数共有三种赋值,默认的值为‘raise’,出现不符合规范的解析时就会报错。
- 可以将errors参数赋值为‘coerce’,在解析的过程中将出错的时间格式设置为NaT。
- 如果不想处理错误的时间格式,可以将errors赋值为‘ignore’,这样就还是原来的格式。
errors{‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’
- If ‘raise’, then invalid parsing will raise an exception.
- If ‘coerce’, then invalid parsing will be set as NaT.
- If ‘ignore’, then invalid parsing will return the input.
本文介绍使用Pandas处理含有异常日期格式的CSV文件时遇到的问题及解决方法。通过调整日期解析器中errors参数的值,可以跳过或转换不符合规范的日期数据。
514

被折叠的 条评论
为什么被折叠?



