Python Pandas 数据标记错误:如何避免因长度不同而导致的错误

Python Pandas Error tokenizing data: How to avoid error caused by different length

我正在尝试使用 pandas read_csv 函数读取 *.dat 文件。

df = pd.read_csv(file, skiprows=0, header=None, sep=" ", parse_dates=[[0, 1]])

数据如下所示:

2019-06-01 04:00:22 PW  100  2000  2000 /// // // // ////// ////// ////
2019-06-01 04:00:32 PW  100  2000  2000 /// // // // ////// ////// ////
2019-06-01 04:00:42 PW  100  2000  2000 /// // // // ////// ////// ////
2019-06-01 04:00:52 PW  100  2000  2000 /// // // // ////// ////// ////
2019-06-01 04:01:02 PW  100  2000  2000 /// // // // ////// ////// ////
2019-06-01 04:01:12 PW  100  2000  2000 /// // // // ////// ////// ////
2019-06-01 04:01:22 PW  100  2000  2000 /// // // // ////// ////// ////
2019-06-01 04:01:32 PW  100  2000  2000 /// // // // ////// ////// ////

我收到标记化错误:

ParserError: Error tokenizing data. C error: Expected 16 fields in line 242, saw 17

我认为这个错误是造成的,因为在第 242 行中第 6 列中的值低于之前的行,例如第 6 列保持 2000 或具有 4 位数字的值(例如 1501),但在第 242 行中它下降到 991(三位数字)。

2019-06-01 04:39:32 PW  100  2000  2000 /// // // // ////// ////// ////
2019-06-01 04:39:42 PW  100  1501  2000 /// // // // ////// ////// ////
2019-06-01 04:39:52 PW  100  1501  2000 /// // // // ////// ////// ////
2019-06-01 04:40:02 PW  100  1501  2000 /// // // // ////// ////// ////
2019-06-01 04:40:12 PW  100  1187  2000 /// // // // ////// ////// ////
2019-06-01 04:40:22 PW  100  1187  2000 /// // // // ////// ////// ////
2019-06-01 04:40:32 PW  100   991  2000 /// // // // ////// ////// ////

我怎样才能摆脱这个错误?

error_bad_lines=False 不是一个选项,因为我需要这些值

您应该使用 sep=" +"sep="\s+" 而不是 sep=" "。对于后者,多个空格被分隔成多个空列,当空格数发生变化时会导致错误。

作为替代方案,您可以指定 delim_whitespace=True 而不是 sepdelimiter