在PyCharm中绘制柱状图时遇KeyError: 'Month'问题求助
KeyError: 'Month'错误 我在PyCharm中尝试绘制柱状图,使用的代码如下:
x=stan2['Month'] y=stan2['distance_kms'] plt.tite('Distance per month') plt.xlabel('Month') plt.ylabl('distance_kms') plt.bar(x,y) plt.show()
运行时出现如下错误:
Traceback (most recent call last):
文件 "E:\Python\PROJECTS\venv\lib\site-packages\pandas\core\indexes\base.py", 行3621, in get_loc
return self._engine.get_loc(casted_key)
文件 "pandas_libs\index.pyx", 行136, in pandas._libs.index.IndexEngine.get_loc
文件 "pandas_libs\index.pyx", 行163, in pandas._libs.index.IndexEngine.get_loc
文件 "pandas_libs\hashtable_class_helper.pxi", 行5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
文件 "pandas_libs\hashtable_class_helper.pxi", 行5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Month'
上述异常直接引发了以下异常:
Traceback (most recent call last):
文件 "E:\Python\PROJECTS\main.py", 行21, in
x=stan2['Month']
文件 "E:\Python\PROJECTS\venv\lib\site-packages\pandas\core\frame.py", 行3505, in getitem
indexer = self.columns.get_loc(key)
文件 "E:\Python\PROJECTS\venv\lib\site-packages\pandas\core\indexes\base.py", 行3623, in get_loc
raise KeyError(key) from err
KeyError: 'Month'
问题原因
- 核心错误:列名不存在
KeyError: 'Month'明确说明DataFramestan2中没有名为'Month'的列,可能的情况包括:
- 列名拼写错误(比如实际是小写
'month'、带空格' Month'、中文'月份'或其他变体) - 数据加载时未正确读取列(比如CSV文件分隔符错误、表头被跳过)
- 之前的数据处理步骤中误删了该列
- 代码中的拼写错误(非当前报错原因,但后续会触发新错误)
plt.tite→ 应为plt.titleplt.ylabl→ 应为plt.ylabel
解决方案
- 确认正确列名
先运行以下代码查看stan2的所有列名:
print(stan2.columns)
根据输出结果,将代码中的'Month'替换为实际存在的列名,同理检查'distance_kms'是否正确。
- 修正代码拼写错误
示例修正后的代码(假设列名确实为'Month'和'distance_kms'):
x = stan2['Month'] y = stan2['distance_kms'] plt.title('Distance per month') plt.xlabel('Month') plt.ylabel('distance_kms') plt.bar(x, y) plt.show()
内容的提问来源于stack exchange,提问作者Arnold Odhiambo

