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

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

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

我的代码很简单:

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

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

文件来自晨星公司


当前回答

这看起来很丑,但你会有你的数据框架

import re
path = 'GOOG Key Ratios.csv'

try:
    data = pd.read_csv(path)
except Exception as e:
    val = re.findall('tokenizing.{1,100}\s*Expected\s*(\d{1,2})\s*',str(e),re.I)
    data = pd.read_csv(path, skiprows=int(val[0])-1)

其他回答

我也有这个问题,但可能是出于不同的原因。我在我的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阅读器来避免。希望熊猫的开发人员能够在未来更容易地处理这种情况。

这肯定是分隔符的问题,因为大多数csv csv都是使用sep='/t'创建的,所以尝试使用分隔符/t的制表符(\t)来读取csv。所以,尝试使用下面的代码行打开。

data=pd.read_csv("File_path", sep='\t')

我从同事那里收到了.csv文件,当我试图使用pd.read_csv()读取csv文件时,我收到了类似的错误。显然,它试图使用第一行来为数据框架生成列,但许多行包含的列比第一行所暗示的要多。我最终通过简单地打开文件并重新保存为.csv并再次使用pd.read_csv()来解决这个问题。

这就是我所做的。

Sep ='::'解决了我的问题:

data=pd.read_csv('C:\\Users\\HP\\Downloads\\NPL ASSINGMENT 2 imdb_labelled\\imdb_labelled.txt',engine='python',header=None,sep='::')

这可能是个问题

数据中的分隔符 第一行,正如@TomAugspurger所指出的

要解决这个问题,请在调用read_csv时尝试指定sep和/或头参数。例如,

df = pandas.read_csv(filepath, sep='delimiter', header=None)

在上面的代码中,sep定义了您的分隔符和header=None,告诉pandas您的源数据没有作为标题/列标题的行。因此,文档说:“如果文件不包含标题行,那么你应该显式地传递header=None”。在这种情况下,pandas会自动为每个字段{0,1,2,…}创建整数索引。

根据文档,分隔符应该不是问题。文档中说“如果sep为None[未指定],将尝试自动确定此值。”然而,我在这方面运气不太好,包括带有明显分隔符的实例。

另一种解决方案可能是尝试自动检测分隔符

# use the first 2 lines of the file to detect separator
temp_lines = csv_file.readline() + '\n' + csv_file.readline()
dialect = csv.Sniffer().sniff(temp_lines, delimiters=';,')

# remember to go back to the start of the file for the next time it's read
csv_file.seek(0) 

df = pd.read_csv(csv_file, sep=dialect.delimiter)