我试图使用熊猫操作.csv文件,但我得到这个错误:

pandas.parser.CParserError:标记数据错误。C错误:第3行有2个字段,见12

我试着读过熊猫的文件,但一无所获。

我的代码很简单:

path = 'GOOG Key Ratios.csv'
#print(open(path).read())
data = pd.read_csv(path)

我该如何解决这个问题?我应该使用csv模块还是其他语言?

文件来自晨星公司


当前回答

有时单元格中有一个逗号“,”。因此,熊猫不能读它。 尝试使用“;”分隔符

df = pd.read_csv(r'yourpath', delimiter=";")

其他回答

对我来说,问题是一个新列被附加到我的CSV盘中。如果我使用error_bad_lines=False,接受的答案解决方案将不起作用,因为未来的每一行都将被丢弃。

这种情况下的解决方案是使用pd.read_csv()中的usecols参数。通过这种方式,我可以只指定需要读入CSV中的列,并且只要标题列存在(并且列名不改变),我的Python代码将对未来的CSV更改保持弹性。

usecols : list-like or callable, optional Return a subset of the columns. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in names or inferred from the document header row(s). For example, a valid list-like usecols parameter would be [0, 1, 2] or ['foo', 'bar', 'baz']. Element order is ignored, so usecols=[0, 1] is the same as [1, 0]. To instantiate a DataFrame from data with element order preserved use pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']] for columns in ['foo', 'bar'] order or pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']] for ['bar', 'foo'] order.

例子

my_columns = ['foo', 'bar', 'bob']
df = pd.read_csv(file_path, usecols=my_columns)

这样做的另一个好处是,如果我只使用一个有18-20列的CSV中的3-4列,我可以将更少的数据加载到内存中。

对于那些在linux操作系统上使用Python 3有类似问题的人。

pandas.errors.ParserError: Error tokenizing data. C error: Calling
read(nbytes) on source failed. Try engine='python'.

试一试:

df.read_csv('file.csv', encoding='utf8', engine='python')

你也可以试试;

data = pd.read_csv('file1.csv', on_bad_lines='skip')

请注意,这将导致有问题的行被跳过。

Edit

对于熊猫< 1.3.0尝试

data = pd.read_csv("file1.csv", error_bad_lines=False)

根据熊猫API参考。

试题:熊猫。read_csv(path, sep = ',',header=None)

问题出在分隔符上。找出在数据中使用的分隔符类型,并如下所示指定它:

data = pd.read_csv('some_data.csv', sep='\t')