Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 指定名称时,Pandas read_csv不会引发错误行的异常_Python_Pandas - Fatal编程技术网

Python 指定名称时,Pandas read_csv不会引发错误行的异常

Python 指定名称时,Pandas read_csv不会引发错误行的异常,python,pandas,Python,Pandas,熊猫读取csv遇到字段过多的行时会引发异常(错误行)。但是,如果指定了参数名称,则不会发生这种情况 示例csv文件的格式为: 1, 2, 3 1, 2, 3 1, 2, 3, 4 read with pd.read_csv(filepath,header=None)正确引发parserror:Error标记化数据。C错误:第3行中预期有3个字段,由于增加了列,因此SAW4 但是,如果将“名称”指定为参数: >>> pd.read_csv(filepath, names=['A

熊猫读取csv遇到字段过多的行时会引发异常(错误行)。但是,如果指定了参数名称,则不会发生这种情况

示例csv文件的格式为:

1, 2, 3
1, 2, 3
1, 2, 3, 4
read with pd.read_csv(filepath,header=None)正确引发parserror:Error标记化数据。C错误:第3行中预期有3个字段,由于增加了列,因此SAW4

但是,如果将“名称”指定为参数:

>>> pd.read_csv(filepath, names=['A', 'B', 'C'], header=None)
   A  B  C
0  1  2  3
1  1  2  3
2  1  2  3
没有引发错误,并且包含了应跳过的“太长/不好”行


有没有一种方法可以指定名称并仍然引发ParserError,这样就可以删除过长/错误的行,并出现错误\u bad\u lines=False?

根据您的输入进行有根据的猜测示例:您所经历的行为可能是由于您隐式地告诉了
pd。read\u csv
以设置
len(usecols)=len(名称)
。因此,将不会导入导致初始异常的列

当您向
名称
添加与csv文件中的列数量相同的标题名称时,您将返回初始异常:

# 1. Determine maximum column count
    sep = ','                                                   # Define separator
    lines = open(filepath).readlines()                        # Open file and read lines
    colcount = max([len(l.strip().split(sep)) for l in lines])  # Count separator

# 2. Add column headers
    df = pd.read_csv(filepath, names = range(colcount))
    # you can rename your columns of interest here in case of error_bad_lines = False

现在,将包含缺少值的列,并返回异常。请注意,这种计算最大列数的方法仅适用于.csv文件。

似乎没有解决方案。您可以使用python的
open()
加载CSV文件,然后在文件字符串中添加新的头,这样您就不会修改磁盘上的原始文件。之后,您可以使用熊猫加载文件字符串。这将保留错误:

#python3
from io import StringIO
import pandas as pd
lines = open('./test.csv', 'r').readlines()
lines = ['A, B, C'] + lines
fileString = '\n'.join(lines)
df = pd.read_csv(StringIO(fileString), sep=",")