参考资料:
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(' ', '_')
当使用Pandas时遇到KeyError:'Date',通常是由于列名含有空格造成。解决方法包括删除列名中的空格或用其他字符替换。例如,可以使用`df.columns=df.columns.str.replace(' ','')`删除空格,或用`df.columns=df.columns.str.replace(' ','_')`将空格替换为下划线。


被折叠的 条评论
为什么被折叠?



