我试图使用熊猫操作.csv文件,但我得到这个错误:
pandas.parser.CParserError:标记数据错误。C错误:第3行有2个字段,见12
我试着读过熊猫的文件,但一无所获。
我的代码很简单:
path = 'GOOG Key Ratios.csv'
#print(open(path).read())
data = pd.read_csv(path)
我该如何解决这个问题?我应该使用csv模块还是其他语言?
文件来自晨星公司
我试图使用熊猫操作.csv文件,但我得到这个错误:
pandas.parser.CParserError:标记数据错误。C错误:第3行有2个字段,见12
我试着读过熊猫的文件,但一无所获。
我的代码很简单:
path = 'GOOG Key Ratios.csv'
#print(open(path).read())
data = pd.read_csv(path)
我该如何解决这个问题?我应该使用csv模块还是其他语言?
文件来自晨星公司
当前回答
对于那些在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')
其他回答
我有一个类似的错误,问题是我有一些转义引号在我的csv文件,需要设置escapechar参数适当。
这肯定是分隔符的问题,因为大多数csv csv都是使用sep='/t'创建的,所以尝试使用分隔符/t的制表符(\t)来读取csv。所以,尝试使用下面的代码行打开。
data=pd.read_csv("File_path", sep='\t')
在处理类似的解析错误时,我发现另一种方法很有用,它使用CSV模块将数据重新路由到pandas df。例如:
import csv
import pandas as pd
path = 'C:/FileLocation/'
file = 'filename.csv'
f = open(path+file,'rt')
reader = csv.reader(f)
#once contents are available, I then put them in a list
csv_list = []
for l in reader:
csv_list.append(l)
f.close()
#now pandas has no problem getting into a df
df = pd.DataFrame(csv_list)
我发现CSV模块对于格式不佳的逗号分隔的文件更加健壮,因此已经成功地用这种方法解决了诸如此类的问题。
这就是我所做的。
Sep ='::'解决了我的问题:
data=pd.read_csv('C:\\Users\\HP\\Downloads\\NPL ASSINGMENT 2 imdb_labelled\\imdb_labelled.txt',engine='python',header=None,sep='::')
使用 熊猫。read_csv (CSVFILENAME,头= None, 9 = " ")
当试图从链接中读取CSV数据时
http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data
我将该网站的数据复制到我的csv文件中。它有额外的空格,所以使用sep =', '并且它工作:)