我试图使用熊猫操作.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文件的第一行和最后两行格式与文件的中间内容不同。

因此,我所做的是将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)

我自己也遇到过几次这样的问题。几乎每次,原因都是我试图打开的文件一开始就不是一个正确保存的CSV。这里的“适当”是指每一行都有相同数量的分隔符或列。

通常发生这种情况是因为我在Excel中打开了CSV,然后不恰当地保存了它。尽管文件扩展名仍然是. CSV,但纯CSV格式已经被改变了。

任何以pandas to_csv保存的文件都将被正确格式化,不应该有这个问题。但如果你用另一个程序打开它,它可能会改变结构。

希望这能有所帮助。

对我来说,问题是一个新列被附加到我的CSV盘中。如果我使用error_bad_lines=False,接受的答案解决方案将不起作用,因为未来的每一行都将被丢弃。

这种情况下的解决方案是使用pd.read_csv()中的usecols参数。通过这种方式,我可以只指定需要读入CSV中的列,并且只要标题列存在(并且列名不改变),我的Python代码将对未来的CSV更改保持弹性。

usecols : list-like or callable, optional Return a subset of the columns. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in names or inferred from the document header row(s). For example, a valid list-like usecols parameter would be [0, 1, 2] or ['foo', 'bar', 'baz']. Element order is ignored, so usecols=[0, 1] is the same as [1, 0]. To instantiate a DataFrame from data with element order preserved use pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']] for columns in ['foo', 'bar'] order or pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']] for ['bar', 'foo'] order.

例子

my_columns = ['foo', 'bar', 'bob']
df = pd.read_csv(file_path, usecols=my_columns)

这样做的另一个好处是,如果我只使用一个有18-20列的CSV中的3-4列,我可以将更少的数据加载到内存中。

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

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

对于那些在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')