pandas - 在数据框中调用列时出错
问题描述
我导入了一个 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'
解决方案
如果 AGTL 是索引列,则首先执行
df.reset_index(inplace=True)
列名有可能包含尾随空格
df.columns = map(str.strip, list(df.columns))
推荐阅读
- karate - 当您可以在没有它的情况下运行测试时,karate-junit5 的目的是什么?
- php - 如何限制 Laravel 中的公共上传文件
- android - 你如何从 Kotlin 的非活动类访问 filesDir
- android - 从数据库调用覆盖确认对话框
- kubernetes - 迁移后的 Nginx 入口配置
- docker - 如何将 Docker 文件夹移动到另一个磁盘?
- android - 如何在 CameraX 中镜像 PreviewView?
- javascript - 防止用户在多项选择题(ReactJS)中两次点击相同的正确答案
- json - 如何在 React.js 中使用 api 变量和动态 js 变量设置 useState 常量变量
- flutter - 将两个文本居中到 AppBar