首页 > 解决方案 > 在数据框中调用列时出错

问题描述

我导入了一个 excel 文件,当我按其名称调用任何列时,它会给我错误。当我尝试导出到 csv 文件时执行一些计算之后,我找到每个(A-cap)的每个列名。

我有以下数据框。

Date            AGTL      ATLH      GHNI
2010-01-05  0.008738  0.009699  0.000000
2010-01-06 -0.003659 -0.000070  0.018519
2010-01-07  0.016423  0.020710  0.006532
2010-01-08 -0.007279 -0.000069  0.002601
2010-01-11  0.000898 -0.007830 -0.026317
2010-01-12 -0.000775 -0.017472  0.023717
2010-01-13  0.005616  0.036284 -0.005222
2010-01-14 -0.005616  0.003747 -0.042787

当我尝试按索引名称调用列时出现以下错误

df['AGTL']
Traceback (most recent call last):

  File "<ipython-input-20-fadf2850086a>", line 1, in <module>
    df['AGTL']

  File "E:\Users\Hussnain\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2927, in __getitem__
    indexer = self.columns.get_loc(key)

  File "E:\Users\Hussnain\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2659, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))

  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'AGTL'

标签: pandassklearn-pandas

解决方案


如果 AGTL 是索引列,则首先执行

df.reset_index(inplace=True)

列名有可能包含尾随空格

 df.columns = map(str.strip, list(df.columns))

推荐阅读