尝试用pandas读取csv时出现问题?

时间:2015-02-10 05:50:41

标签: python python-2.7 csv pandas io

我有一个csv文件,如下所示:

Id, text, label
10101, string, label

然后我想用熊猫放入数据框,所以我这样做:

 df = pd.read_csv('/path/.csv')
 X, y = df['text'], df['label']

我得到了这个追溯:

Traceback (most recent call last):
  File "/Users/user/test.py", line 27, in <module>
    X, y, = df['text'], df['label']
  File "/usr/local/lib/python2.7/site-packages/pandas/core/frame.py", line 1780, in __getitem__
    return self._getitem_column(key)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/frame.py", line 1787, in _getitem_column
    return self._get_item_cache(key)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/generic.py", line 1058, in _get_item_cache
    values = self._data.get(item)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/internals.py", line 2889, in get
    loc = self.items.get_loc(item)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/index.py", line 1400, in get_loc
    return self._engine.get_loc(_values_from_object(key))
  File "pandas/index.pyx", line 134, in pandas.index.IndexEngine.get_loc (pandas/index.c:3807)
  File "pandas/index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas/index.c:3687)
  File "pandas/hashtable.pyx", line 696, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12310)
  File "pandas/hashtable.pyx", line 704, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12261)
KeyError: 'text'

有人能帮我理解发生了什么以及如何用熊猫正确读取这个文件吗?先谢谢你们。

1 个答案:

答案 0 :(得分:1)

CSV文件中的标题是:

Id, text, label

请注意,第2列和第3列的列标题中有前导空格。您可以通过包含空格来访问该列:

x, y = df[' text'], df[' label']

或指定skipinitialspace参数:

df = pd.read_csv('/path/x.csv', skipinitialspace=True)
x, y = df['text'], df['label']

后者也会从列数据中删除初始空格。