我的csv如下(MQM Q.csv):
Date-Time,Value,Grade,Approval,Interpolation Code
31/08/2012 12:15:00,,41,1,1
31/08/2012 12:30:00,,41,1,1
31/08/2012 12:45:00,,41,1,1
31/08/2012 13:00:00,,41,1,1
31/08/2012 13:15:00,,41,1,1
31/08/2012 13:30:00,,41,1,1
31/08/2012 13:45:00,,41,1,1
31/08/2012 14:00:00,,41,1,1
31/08/2012 14:15:00,,41,1,1
前几行没有“值”条目,但它们稍后开始。
这是我的代码:
import pandas as pd
from StringIO import StringIO
Q = pd.read_csv(StringIO("""/cygdrive/c/temp/MQM Q.csv"""), header=0, usecols=["Date-Time", "Value"], parse_dates=True, dayfirst=True, index_col=0)
我收到以下错误:
Traceback (most recent call last):
File "daily.py", line 4, in <module>
Q = pd.read_csv(StringIO("""/cygdrive/c/temp/MQM Q.csv"""), header=0, usecols=["Date-Time", "Value"], parse_dates=True, dayfirst=True, index_col=0)
File "/usr/lib/python2.7/site-packages/pandas-0.14.0-py2.7-cygwin-1.7.30-x86_64.egg/pandas/io/parsers.py", line 443, in parser_f
return _read(filepath_or_buffer, kwds)
File "/usr/lib/python2.7/site-packages/pandas-0.14.0-py2.7-cygwin-1.7.30-x86_64.egg/pandas/io/parsers.py", line 228, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "/usr/lib/python2.7/site-packages/pandas-0.14.0-py2.7-cygwin-1.7.30-x86_64.egg/pandas/io/parsers.py", line 533, in __init__
self._make_engine(self.engine)
File "/usr/lib/python2.7/site-packages/pandas-0.14.0-py2.7-cygwin-1.7.30-x86_64.egg/pandas/io/parsers.py", line 670, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "/usr/lib/python2.7/site-packages/pandas-0.14.0-py2.7-cygwin-1.7.30-x86_64.egg/pandas/io/parsers.py", line 1067, in __init__
col_indices.append(self.names.index(u))
ValueError: 'Value' is not in list
答案 0 :(得分:3)
这似乎是csv解析器的一个错误,首先这有效:
df = pd.read_csv('MQM Q.csv')
这也有效:
df = pd.read_csv('MQM Q.csv', usecols=['Value'])
但如果我想要Date-Time
,那么它会失败并显示与您相同的错误消息。
所以我注意到它是utf-8编码的,所以我使用notepad ++转换为ANSI并且它工作了,然后我尝试了没有BOM的utf-8,它也有用。
然后我将它转换为utf-8(可能现在有一个BOM)并且它失败并出现与之前相同的错误,所以我不认为你现在正在对此进行成像,这看起来像一个bug。 / p>
我使用的是python 3.3,pandas 0.14和numpy 1.8.1
要解决这个问题:
df = pd.read_csv('MQM Q.csv', usecols=[0,1], parse_dates=True, dayfirst=True, index_col=0)
这会将您的索引设置为Date-Time列,该列将正确转换为datetimeindex。
In [40]:
df.index
Out[40]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-08-31 12:15:00, ..., 2013-11-28 10:45:00]
Length: 43577, Freq: None, Timezone: None
答案 1 :(得分:0)
您的代码应该读取(文件名中不需要StringIO!):
import pandas as pd
Q = pd.read_csv("/cygdrive/c/temp/MQM Q.csv"), header=0, usecols=["Date-Time", "Value"], parse_dates=True, dayfirst=True, index_col=0)
否则/当前pandas正试图以DataFrame的形式读取字符串(路径):
In [11]: pd.read_csv(StringIO("""/cygdrive/c/temp/MQM Q.csv"""))
Out[11]:
Empty DataFrame
Columns: [/cygdrive/c/temp/MQM Q.csv]
Index: []
这显然不是你想要的(因此你看到Value不是列例外)。
答案 2 :(得分:0)
以下适用于我(我将CSV文件与脚本放在同一目录中,但这无关紧要)。我在Mac上运行以下脚本,而不是Cygwin,但它应该以相同的方式运行:
import pandas as pd
Q = pd.read_csv("MQM Q.csv",
header=0,
parse_dates=True,
dayfirst=True,
index_col=0,
usecols=["Date-Time", "Value"])
print Q