我试图使用熊猫操作.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模块还是其他语言?
文件来自晨星公司
当前回答
我也有这个问题,但可能是出于不同的原因。我在我的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模块将数据重新路由到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模块对于格式不佳的逗号分隔的文件更加健壮,因此已经成功地用这种方法解决了诸如此类的问题。
在我的例子中,分隔符不是默认的“,”,而是Tab。
pd.read_csv(file_name.csv, sep='\\t',lineterminator='\\r', engine='python', header='infer')
注意:“\t”并不像某些来源所建议的那样有效。“\\t”是必需的。
使用 熊猫。read_csv (CSVFILENAME,头= None, 9 = " ")
当试图从链接中读取CSV数据时
http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data
我将该网站的数据复制到我的csv文件中。它有额外的空格,所以使用sep =', '并且它工作:)
您的CSV文件可能有可变的列数,read_csv从前几行推断出列数。在这种情况下有两种解决方法:
1)将CSV文件更改为具有最大列数的虚拟第一行(并指定header=[0])
2)或者使用names = list(range(0,N)),其中N是最大列数。
这就是我所做的。
Sep ='::'解决了我的问题:
data=pd.read_csv('C:\\Users\\HP\\Downloads\\NPL ASSINGMENT 2 imdb_labelled\\imdb_labelled.txt',engine='python',header=None,sep='::')