keyerror 问题

参考资料:
https://www.geeksforgeeks.org/remove-spaces-from-column-names-in-pandas/

错误反馈:

Traceback (most recent call last):
  File "D:\SoftWare\Python\Python38\lib\site-packages\pandas\core\indexes\base.py", line 3621, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas\_libs\index.pyx", line 136, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 163, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Date'

原因分析: 找不到这个Key,columns里存在空格

解决方法:
删除columns里的空格或者用其他字符代替

# 删除
df.columns = df.columns.str.replace(' ', '')

# 替代
df.columns = df.columns.str.replace(' ', '_')

你可能感兴趣的:(bug笔记,python,机器学习,开发语言)