python - 在 Pandas read_csv 期间标记化数据时出错。如何真正看到坏线?

标签 python csv pandas

我有一个很大的 csv,我按如下方式加载

df=pd.read_csv('my_data.tsv',sep='\t',header=0, skiprows=[1,2,3])

我在加载过程中遇到了几个错误。

  1. 首先,如果我不指定 warn_bad_lines=True,error_bad_lines=False,我会得到:

    Error tokenizing data. C error: Expected 22 fields in line 329867, saw 24

  2. 其次,如果我使用上面的选项,我现在得到:

    CParserError: Error tokenizing data. C error: EOF inside string starting at line 32357585

问题是:我如何查看这些坏行以了解发生了什么?是否可以让 read_csv 返回这些伪造的行?

我尝试了以下提示(Pandas ParserError EOF character when reading multiple csv files to HDF5):

from pandas import parser

try:
  df=pd.read_csv('mydata.tsv',sep='\t',header=0, skiprows=[1,2,3])
except (parser.CParserError) as detail:
  print  detail

但还是得到了

Error tokenizing data. C error: Expected 22 fields in line 329867, saw 24

最佳答案

我会分两部分给出我的答案:

第 1 部分: 运算符(operator)询问如何输出这些错误的行,为了回答这个问题,我们可以在像这样的简单代码中使用 python csv 模块:

import csv
file = 'your_filename.csv' # use your filename
lines_set = set([100, 200]) # use your bad lines numbers here

with open(file) as f_obj:
    for line_number, row in enumerate(csv.reader(f_obj)):
        if line_number > max(lines_set):
            break
        elif line_number in lines_set: # put your bad lines numbers here
            print(line_number, row)

我们也可以把它放在更通用的函数中:

import csv


def read_my_lines(file, lines_list, reader=csv.reader):
    lines_set = set(lines_list)
    with open(file) as f_obj:
        for line_number, row in enumerate(csv.reader(f_obj)):
            if line_number > max(lines_set):
                break
            elif line_number in lines_set:
                print(line_number, row)


if __name__ == '__main__':
    read_my_lines(file='your_filename.csv', lines_list=[100, 200])

part2:你得到错误的原因:

如果没有您使用的文件样本,很难诊断这样的问题。 但你应该试试这个..

pd.read_csv(filename)

是否解析文件没有错误?如果是,我会解释原因。

列数是从第一行推断出来的。

通过使用 skiprows 和 header=0,您转义了前 3 行,我猜其中包含列名或应该包含正确列数的标题。

基本上你限制了解析器正在做什么。

所以在不使用 skiprows 或 header=0 的情况下进行解析,然后重新索引到您稍后需要的内容。

注意:

如果您不确定文件中使用的分隔符是什么,请使用 sep=None,但这样会更慢。

来自 pandas.read_csv 文档:

sep : str, default ‘,’ Delimiter to use. If sep is None, the C engine cannot automatically detect the separator, but the Python parsing engine can, meaning the latter will be used and automatically detect the separator by Python’s builtin sniffer tool, csv.Sniffer. In addition, separators longer than 1 character and different from '\s+' will be interpreted as regular expressions and will also force the use of the Python parsing engine. Note that regex delimiters are prone to ignoring quoted data. Regex example: '\r\t'

link

关于python - 在 Pandas read_csv 期间标记化数据时出错。如何真正看到坏线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38902553/

相关文章:

python - 根据日期对 CSV 文件进行排序

mysql - 将 CSV 数据导入 SQL 数据库

python - 通过多个正则表达式对 DataFrame 列进行排序

python - 类型错误 : data type not understood while parsing CSV with Pandas

python - Django 路由问题

python - 加入: string and absolute path with os.路径

c++ - 如何在 C++ 中传递/捕获/响应 Python 的 KeyboardInterrupt?

python - 使用 Pandas 读取 CSV 日期返回日期时间而不是时间戳

python - 如何找到两个变量之间的相关性但跨越不同的时间线('lagged correlation')

python - 在二维数组中创建黑白棋盘