在Pandas中使用read_csv时使用跳过线时出错

时间:2015-05-23 12:28:52

标签: python csv pandas

我正在尝试使用Pandas库中的read_csv将数据框导入Python。数据文件的顶部(annual_precip.csv)如下所示:

Average annual precipitation and land area ,,
,mm/year,thousand km^2
country,precip,area
Afghanistan,327,652.2
Albania,1485,27.4
Algeria,89,2381.7
American Samoa,,0.2

这是我的代码:

from pandas import read_csv
read_csv('annual_precip.csv', index_col = [0], skiprows = 2)

这会产生以下错误:

Traceback (most recent call last):`

File "<ipython-input-894-742b462476f6>", line 1, in <module>
rain =read_csv('exploratory_computing_with_python/notebook5/annual_precip.csv', skiprows = 2, index_col = [0])`

File "/Users/jakoberickson/anaconda/lib/python2.7/site-packages/pandas/io/parsers.py", line 465, in parser_f
return _read(filepath_or_buffer, kwds)`

File "/Users/jakoberickson/anaconda/lib/python2.7/site-packages/pandas/io/parsers.py", line 241, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)`

File "/Users/jakoberickson/anaconda/lib/python2.7/site-packages/pandas/io/parsers.py", line 557, in __init__
self._make_engine(self.engine)`

File "/Users/jakoberickson/anaconda/lib/python2.7/site-packages/pandas/io/parsers.py", line 694, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)`

File "/Users/jakoberickson/anaconda/lib/python2.7/site-packages/pandas/io/parsers.py", line 1061, in __init__
self._reader = _parser.TextReader(src, **kwds)`

File "pandas/parser.pyx", line 512, in pandas.parser.TextReader.__cinit__ (pandas/parser.c:4804)`

ValueError: No columns to parse from file`

当我跳过1或0行但我的列名称不正确时,我没有收到任何错误。我在Yosemite的Anaconda包中运行Spyder 2.3.4,如果这有任何区别的话。

2 个答案:

答案 0 :(得分:3)

我将pandas更新为&#39; 0.16.1&#39;现在我没有任何问题。谢谢你的帮助@Wajdi Farhani

答案 1 :(得分:2)

它适用于您示例中的csv示例,但问题是您的csv文件包含不可打印的字符。

试试这个:

df = pd.read_csv('annual_precip.csv', index_col = [0],  encoding='utf-8', skiprows = 2)