使用pandas从excel表格中取一列值报错,注意空格
使用pandas从excel数据中取某一列时报错:
KeyError Traceback (most recent call last)
E:\ProgramFiles\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3360 try:
-> 3361 return self._engine.get_loc(casted_key)
3362 except KeyError as err:
E:\ProgramFiles\Anaconda3\lib\site-packages\pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
E:\ProgramFiles\Anaconda3\lib\site-packages\pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: ‘Race’
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
in
—-> 1 df[‘Race’]
E:\ProgramFiles\Anaconda3\lib\site-packages\pandas\core\frame.py in getitem(self, key)
3456 if self.columns.nlevels > 1:
3457 return self._getitem_multilevel(key)
-> 3458 indexer = self.columns.get_loc(key)
3459 if is_integer(indexer):
3460 indexer = [indexer]
E:\ProgramFiles\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3361 return self._engine.get_loc(casted_key)
3362 except KeyError as err:
-> 3363 raise KeyError(key) from err
3364
3365 if is_scalar(key) and isna(key) and not self.hasnans:
KeyError: ‘Race’
原因:这个列名写错了,没有加空格。直接用别人的excel表格和代码,运行时报错,发现在原文档中的这一列后面有一股空格!!!所有一般的列名都最好用_分割,用空格很容易忽略。
一个相同的案例:链接