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

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

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

我的代码很简单:

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

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

文件来自晨星公司


当前回答

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

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

其他回答

检查是否使用正确的分隔符加载csv。

df = pd.read_csv(csvname, header=0, sep=",")

我遇到了这个问题,我试图在不传递列名的情况下读取CSV。

df = pd.read_csv(filename, header=None)

我事先在一个列表中指定了列名,然后将它们传递到名称中,它立即解决了这个问题。如果您没有设置列名,您可以创建与数据中可能存在的最大列数量一样多的占位符名称。

col_names = ["col1", "col2", "col3", ...]
df = pd.read_csv(filename, names=col_names)

你也可以试试;

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参考。

对我来说,问题是一个新列被附加到我的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列,我可以将更少的数据加载到内存中。

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

这个错误给出了解决问题“Expected 2 fields in line 3, saw 12”的线索,saw 12表示第二行长度为12,第一行长度为2。

当您有如下所示的数据时,如果您跳过行,那么大部分数据将被跳过

data = """1,2,3
1,2,3,4
1,2,3,4,5
1,2
1,2,3,4"""

如果您不想跳过任何行,请执行以下操作

#First lets find the maximum column for all the rows
with open("file_name.csv", 'r') as temp_f:
    # get No of columns in each line
    col_count = [ len(l.split(",")) for l in temp_f.readlines() ]

### Generate column names  (names will be 0, 1, 2, ..., maximum columns - 1)
column_names = [i for i in range(max(col_count))] 

import pandas as pd
# inside range set the maximum value you can see in "Expected 4 fields in line 2, saw 8"
# here will be 8 
data = pd.read_csv("file_name.csv",header = None,names=column_names )

使用range而不是手动设置名称,因为当您有很多列时,这样做会很麻烦。

此外,如果需要使用均匀的数据长度,可以将NaN值填充为0。如。对于聚类(k-means)

new_data = data.fillna(0)