我试图使用熊猫操作.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模块还是其他语言?
文件来自晨星公司
当前回答
以下是对我有用的(我张贴了这个答案,因为我在谷歌协作笔记本中特别遇到了这个问题):
df = pd.read_csv("/path/foo.csv", delimiter=';', skiprows=0, low_memory=False)
其他回答
以下是对我有用的(我张贴了这个答案,因为我在谷歌协作笔记本中特别遇到了这个问题):
df = pd.read_csv("/path/foo.csv", delimiter=';', skiprows=0, low_memory=False)
对于这个问题,我遇到了多种解决方案。很多人也给出了最好的解释。但对于初学者来说,我认为以下两种方法就足够了:
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')
对我来说,问题是一个新列被附加到我的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列,我可以将更少的数据加载到内存中。
解析器被文件头弄糊涂了。它读取第一行并从该行推断列数。但是前两行并不能代表文件中的实际数据。
用data = pd试试。read_csv(路径,skiprows = 2)
试题:熊猫。read_csv(path, sep = ',',header=None)