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

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

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

我的代码很简单:

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

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

文件来自晨星公司


当前回答

有时候问题不在于如何使用python,而在于如何处理原始数据。 我得到了这个错误信息

Error tokenizing data. C error: Expected 18 fields in line 72, saw 19.

结果发现,在列描述中有时会有逗号。这意味着需要清理CSV文件或使用另一个分隔符。

其他回答

在我的例子中,这是因为csv文件的第一行和最后两行格式与文件的中间内容不同。

因此,我所做的是将csv文件作为字符串打开,解析字符串的内容,然后使用read_csv获取数据帧。

import io
import pandas as pd

file = open(f'{file_path}/{file_name}', 'r')
content = file.read()

# change new line character from '\r\n' to '\n'
lines = content.replace('\r', '').split('\n')

# Remove the first and last 2 lines of the file
# StringIO can be considered as a file stored in memory
df = pd.read_csv(StringIO("\n".join(lines[2:-2])), header=None)

你可以使用:

pd.read_csv("mycsv.csv", delimiter=";")

熊猫1.4.4

它可以是文件的分隔符,将其作为文本文件打开,查找分隔符。然后,您将拥有可以为空且未命名的列,因为行包含太多分隔符。

因此,您可以使用pandas来处理它们并检查值。对我来说,这比在我的情况下跳过台词要好。

我有一个类似的错误,问题是我有一些转义引号在我的csv文件,需要设置escapechar参数适当。

我也有这个问题,但可能是出于不同的原因。我在我的CSV中有一些尾随逗号,添加了熊猫试图读取的额外列。使用以下方法是可行的,但它只是忽略了不好的行:

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

如果你想让代码行看起来很丑,你可以这样做:

line     = []
expected = []
saw      = []     
cont     = True 

while cont == True:     
    try:
        data = pd.read_csv('file1.csv',skiprows=line)
        cont = False
    except Exception as e:    
        errortype = e.message.split('.')[0].strip()                                
        if errortype == 'Error tokenizing data':                        
           cerror      = e.message.split(':')[1].strip().replace(',','')
           nums        = [n for n in cerror.split(' ') if str.isdigit(n)]
           expected.append(int(nums[0]))
           saw.append(int(nums[2]))
           line.append(int(nums[1])-1)
         else:
           cerror      = 'Unknown'
           print 'Unknown Error - 222'

if line != []:
    # Handle the errors however you want

我接着写了一个脚本,将这些行重新插入到DataFrame中,因为坏的行将由上述代码中的变量“line”给出。这一切都可以通过简单地使用csv阅读器来避免。希望熊猫的开发人员能够在未来更容易地处理这种情况。

标记数据错误。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)