我试图使用熊猫操作.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。
df = pd.read_csv(csvname, header=0, sep=",")
其他回答
我相信解决方案,
,engine='python'
, error_bad_lines = False
如果它是虚拟列并且你想要删除它,这将是很好的。 在我的例子中,第二行确实有更多的列,我希望这些列被积分,并且有列数= MAX(列)。
请参考下面我无法阅读的解决方案:
try:
df_data = pd.read_csv(PATH, header = bl_header, sep = str_sep)
except pd.errors.ParserError as err:
str_find = 'saw '
int_position = int(str(err).find(str_find)) + len(str_find)
str_nbCol = str(err)[int_position:]
l_col = range(int(str_nbCol))
df_data = pd.read_csv(PATH, header = bl_header, sep = str_sep, names = l_col)
你可以使用:
pd.read_csv("mycsv.csv", delimiter=";")
熊猫1.4.4
它可以是文件的分隔符,将其作为文本文件打开,查找分隔符。然后,您将拥有可以为空且未命名的列,因为行包含太多分隔符。
因此,您可以使用pandas来处理它们并检查值。对我来说,这比在我的情况下跳过台词要好。
在我的例子中,分隔符不是默认的“,”,而是Tab。
pd.read_csv(file_name.csv, sep='\\t',lineterminator='\\r', engine='python', header='infer')
注意:“\t”并不像某些来源所建议的那样有效。“\\t”是必需的。
我也有这个问题,但可能是出于不同的原因。我在我的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阅读器来避免。希望熊猫的开发人员能够在未来更容易地处理这种情况。
以下是对我有用的(我张贴了这个答案,因为我在谷歌协作笔记本中特别遇到了这个问题):
df = pd.read_csv("/path/foo.csv", delimiter=';', skiprows=0, low_memory=False)