我试图使用熊猫操作.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文件,需要设置escapechar参数适当。
其他回答
在我的例子中,这是因为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)
我使用的数据集有很多引号(")使用无关的格式。我能够通过包含read_csv()的这个参数来修复这个错误:
quoting=3 # 3 correlates to csv.QUOTE_NONE for pandas
使用 熊猫。read_csv (CSVFILENAME,头= None, 9 = " ")
当试图从链接中读取CSV数据时
http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data
我将该网站的数据复制到我的csv文件中。它有额外的空格,所以使用sep =', '并且它工作:)
对于这个问题,我遇到了多种解决方案。很多人也给出了最好的解释。但对于初学者来说,我认为以下两种方法就足够了:
import pandas as pd
#Method 1
data = pd.read_csv('file1.csv', error_bad_lines=False)
#Note that this will cause the offending lines to be skipped.
#Method 2 using sep
data = pd.read_csv('file1.csv', sep='\t')
在我的例子中,分隔符不是默认的“,”,而是Tab。
pd.read_csv(file_name.csv, sep='\\t',lineterminator='\\r', engine='python', header='infer')
注意:“\t”并不像某些来源所建议的那样有效。“\\t”是必需的。