读取缺少 EOL 的 CSV 文件

Read CSV File with some EOL missing

我需要将一堆 csv 文件读取到 pandas 数据帧,我正在 运行 读取一些缺少行尾字符的文件。它根本不存在。由于 "different number of columns".

pandas.read_csv 不会阅读它们
Time; A; B; C
12:00; 1; 2; 3
12:01; 4; 5; 6; 12:02; 7; 8; 9
12:03; 10; 11; 12
12:04; 13; 14; 15

幸运的是,所有这些错误都在第一列之前,所以我可以查找时间(没有其他列有时间)。在这种情况下,我只需要在 12:02 之前插入一个 CR/LF 然后读取到数据帧:

Time; A; B; C
12:00; 1; 2; 3
12:01; 4; 5; 6; 
12:02; 7; 8; 9
12:03; 10; 11; 12
12:04; 13; 14; 15

read_csv()之前有没有有效的方法来做到这一点?还是我需要先打开每个文件,查看每一行,替换,关闭,然后用 pandas 读取?


使用:python3.5.2 , pandas 0.22.0

如果你有违规行为,你可以尝试预处理 csv

例如:

import pandas as pd

res = []
with open(filename) as infile:             #Read CSV
    header = next(infile).split(";")       #Get Header
    for line in infile:                    #Iterate each line
        val = line.split(";")
        if len(val) == 4:                  #Check if 4 elements in each line
            res.append(val)
        else:
            res.extend( [val[i:i+4] for i in range(0, len(val), 4)] )     #Else split it. 

df = pd.DataFrame(res, columns=header)
print(df)

输出:

     Time    A    B    C\n
0   12:00    1    2    3\n
1   12:01    4    5      6
2   12:02    7    8    9\n
3   12:03   10   11   12\n
4   12:04   13   14     15