Python Pandas 错误标记数据 : How to avoid error caused by different length

标签 python pandas tokenize

我正在尝试使用 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

关于Python Pandas 错误标记数据 : How to avoid error caused by different length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59174339/

相关文章:

python - 在 pandas 中,您可以按均值聚合并将其舍入到最接近的整数吗?

python - 将 .isin 应用于 pandas 中每一行的有效方法

ruby - StringScanner 正在匹配一个字符串,就好像它向后一个位置一样

python - 标记化 python 源代码示例(在 Python 中)

python 字符串每两个字符到字节 - 快速完成

python - 如何操作 numpy 数组以用于 ESRI 的 arcpy.da.NumPyArrayToTable

python - pandas,使用func pandas.Series.value_counts后如何获取索引?

python - 如何在 Python 中对这 2 个循环进行向量化?

python - 在映射函数中除以 0

c++ - 标记一个字符串,并将每个分隔符放在它自己的标记中