写在前面

今天在用爬虫及Pandas更新股票日线数据的时候发现KeyError报错,后面跟了一个DataFrame列索引,一开始以为是索引修改列的值导致的问题,修改为.loc错误依然出现,后来将列值的内容修改方法改为.apply(lambda)问题依然出现。就在百思不得其解时,我发现了问题所在。。。

报错详细信息

主要配置及环境

  • Windows 10 64位
  • Python:3.6.8
  • Pandas:1.0.3

报错内容

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报错的时候,需要先查看数据是不是存在空值,尤其是程序里面有爬虫代码的时候,更需要注意。网站经常在变,不过基本上没有大的变化,万变不离其宗,掌握大的方法就可以了。

原文地址:https://zorchp.blog.csdn.net/article/details/105693620

相关文章: