我试图使用熊猫操作.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)

其他回答

我有一个类似的错误,问题是我有一些转义引号在我的csv文件,需要设置escapechar参数适当。

解析器被文件头弄糊涂了。它读取第一行并从该行推断列数。但是前两行并不能代表文件中的实际数据。

用data = pd试试。read_csv(路径,skiprows = 2)

在我的例子中,这是因为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)

大多数有用的答案已经提到了,但是我建议将pandas数据框架保存为parquet文件。Parquet文件没有这个问题,同时它们是内存高效的。

问题可能与文件问题,在我的情况下,问题在重命名文件后得到解决。还没弄清楚原因。