Python 官方文档:入门教程 => 点击学习
目录写在前面报错详细信息问题解决举一反三写在前面 今天在用爬虫及pandas更新股票日线数据的时候发现KeyError报错,后面跟了一个DataFrame列索引,一开始以为是索引修改
今天在用爬虫及pandas更新股票日线数据的时候发现KeyError报错,后面跟了一个DataFrame列索引,一开始以为是索引修改列的值导致的问题,修改为.loc错误依然出现,后来将列值的内容修改方法改为.apply(lambda)问题依然出现。就在百思不得其解时,我发现了问题所在。。。
主要配置及环境
报错内容
Traceback (most recent call last):
File "E:\py36\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
return self._engine.get_loc(key)
File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'turnover'During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:\aaaDesktop\test.py", line 34, in <module>
df['turnover'] = df['turnover'] * 100
File "E:\py36\lib\site-packages\pandas\core\frame.py", line 2800, in __getitem__
indexer = self.columns.get_loc(key)
File "E:\py36\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'turnover'
[Finished in 5.4s]
代码主要流程:
抓取Sina财经的日线数据接口(有需要者可以私信我了解更多),抓取交易日所有交易的股票数据,进行数据处理、整合为DataFrame并逐行读取存入CSV文件。
既然不是索引的问题,那就只有一直往上追溯,结果发现,在 设置抓取函数的循环跳出条件 时,由于各大网站最近在备案&更新,导致空数据页面显示内容变成了一个字符串类型的空列表。。。于是只要将循环跳出的条件设置为:
if eval(content) == []:
就可以解决问题了。
由于这次的经验,我发现在出现KeyError报错的时候,需要先查看数据是不是存在空值,尤其是程序里面有爬虫代码的时候,更需要注意。网站经常在变,不过基本上没有大的变化,万变不离其宗,掌握大的方法就可以了。
到此这篇关于Pandas出现KeyError的问题解决及分析的文章就介绍到这了,更多相关Pandas KeyError内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Pandas出现KeyError的问题解决及分析
本文链接: https://www.lsjlt.com/news/177974.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0