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

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

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

我的代码很简单:

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

我该如何解决这个问题?我应该使用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)

其他回答

这可能是个问题

数据中的分隔符 第一行,正如@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)

我有一个已有行号的数据集,我使用index_col:

pd.read_csv('train.csv', index_col=0)

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

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)

在我的例子中,问题是熊猫版本,所以熊猫1.3.5就像一个魅力。

我有一个类似的问题,而试图读取一个制表符分隔表与空格,逗号和引号:

1115794 4218    "k__Bacteria", "p__Firmicutes", "c__Bacilli", "o__Bacillales", "f__Bacillaceae", ""
1144102 3180    "k__Bacteria", "p__Firmicutes", "c__Bacilli", "o__Bacillales", "f__Bacillaceae", "g__Bacillus", ""
368444  2328    "k__Bacteria", "p__Bacteroidetes", "c__Bacteroidia", "o__Bacteroidales", "f__Bacteroidaceae", "g__Bacteroides", ""



import pandas as pd
# Same error for read_table
counts = pd.read_csv(path_counts, sep='\t', index_col=2, header=None, engine = 'c')

pandas.io.common.CParserError: Error tokenizing data. C error: out of memory

这表明它与C解析引擎(这是默认的)有关。也许换成python会改变一切

counts = pd.read_table(path_counts, sep='\t', index_col=2, header=None, engine='python')

Segmentation fault (core dumped)

这是一个不同的错误。 如果我们继续尝试从表中删除空格,来自python-engine的错误再次改变:

1115794 4218    "k__Bacteria","p__Firmicutes","c__Bacilli","o__Bacillales","f__Bacillaceae",""
1144102 3180    "k__Bacteria","p__Firmicutes","c__Bacilli","o__Bacillales","f__Bacillaceae","g__Bacillus",""
368444  2328    "k__Bacteria","p__Bacteroidetes","c__Bacteroidia","o__Bacteroidales","f__Bacteroidaceae","g__Bacteroides",""


_csv.Error: '   ' expected after '"'

很明显,熊猫在解析我们的行时遇到了问题。为了用python引擎解析一个表,我需要事先从表中删除所有的空格和引号。与此同时,c引擎不断崩溃,即使逗号在行。 为了避免创建一个带有替换的新文件,我这样做了,因为我的表很小:

from io import StringIO
with open(path_counts) as f:
    input = StringIO(f.read().replace('", ""', '').replace('"', '').replace(', ', ',').replace('\0',''))
    counts = pd.read_table(input, sep='\t', index_col=2, header=None, engine='python')

博士tl; 更改解析引擎,尽量避免在数据中使用任何非分隔的引号/逗号/空格。