KeyError(f"None of [{key}] are in the [{axis_name}]")含义及代码报错排查
Pandas绘图时的KeyError问题解析
一、KeyError(f"None of [{key}] are in the [{axis_name}]")的含义
这个错误是Pandas的典型报错,意思是你试图访问的键(key)不存在于指定的轴(axis)中。如果报错里的轴是columns,就表示你想用某个/些值作为列名去索引DataFrame,但这些值根本不是该DataFrame的列名。
二、代码场景与报错
你通过两个不同DataFrame的列拼接生成了joined_df:
创建DataFrame的代码
import pandas as pd pvgis_df = pd.read_csv(pvgis_file) month = pd.Series(pvgis_df["Month"],) pvgis_generated = pd.Series(pvgis_df["Avg Monthly Energy Production"],) pvoutput_generated = pd.Series(pvoutput_df["Generated (KWh)"],) frame = { "Month": month, "PVGIS Generated": pvgis_generated, "PVOUTPUT Generated": pvoutput_generated } joined_df = pd.DataFrame(frame)
生成的DataFrame输出
Month PVGIS Generated PVOUTPUT Generated 0 1.0 107434.69 80608.001709 1 2.0 112428.41 106485.000610 2 3.0 153701.40 132772.003174 3 4.0 179380.47 148830.993652 4 5.0 200402.90 177705.001831 5 6.0 211507.83 173893.005371 6 7.0 233932.95 182261.993408 7 8.0 223986.41 174046.005249 8 9.0 178682.94 142970.993042 9 10.0 142141.02 107087.997437 10 11.0 108498.34 73358.001709 11 12.0 101886.06 73003.997803
尝试的绘图代码
from matplotlib import pyplot as plt label = [ df["Month"], df["PVGIS Generated"], df["PVOUTPUT Generated"] ] figure_title = f"{plt.xlabel} VS {plt.ylabel}" fig = plt.figure(figure_title) fig.set_size_inches(13.6, 7.06) plot_no = df.shape filename = f"{folder}_joined" color="blue" plt.legend() plt.xlabel("Month") plt.ylabel("Generated") plt.grid() plt.margins(x=0) plt.ticklabel_format(useOffset=False, axis="y", style="plain") plt.bar(df[label[0]], df[label[1]]) plt.bar(df[label[0]], df[label[2]]) plt.show() plt.close()
触发的报错
KeyError: "None of [Float64Index([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0], dtype='float64')] are in the [columns]
三、错误原因与修正
核心问题:索引方式完全错误
你在绘图代码里犯了两个关键错误:
- 变量名不匹配:你创建的DataFrame是
joined_df,但绘图时用的是df,如果没有提前将joined_df赋值给df,会直接触发NameError; - 用列的取值当列名索引:
label = [df["Month"], df["PVGIS Generated"], ...]里的每个元素都是Pandas Series(即列的具体数值),而非列名字符串。之后df[label[0]]相当于用Month列的所有数值(1.0、2.0...)作为列名去取DataFrame的列,这些数值根本不是列名,自然触发KeyError。
此外还有几个小问题:
figure_title = f"{plt.xlabel} VS {plt.ylabel}":plt.xlabel是函数对象,不是字符串,应该手动指定标题;plt.legend()调用过早,此时还没有绘制任何带标签的图形,图例会是空的;- 两组柱状图没有设置宽度,会完全重叠。
修正后的完整代码
import pandas as pd from matplotlib import pyplot as plt # 读取数据 pvgis_df = pd.read_csv(pvgis_file) pvoutput_df = pd.read_csv(pvoutput_file) # 补充缺失的读取代码 # 创建合并后的DataFrame frame = { "Month": pvgis_df["Month"], "PVGIS Generated": pvgis_df["Avg Monthly Energy Production"], "PVOUTPUT Generated": pvoutput_df["Generated (KWh)"] } joined_df = pd.DataFrame(frame) # 绘图部分 fig = plt.figure("月发电量对比") fig.set_size_inches(13.6, 7.06) # 直接取出列的数值,而非尝试用数值当列名索引 x = joined_df["Month"] pvgis_data = joined_df["PVGIS Generated"] pvoutput_data = joined_df["PVOUTPUT Generated"] # 设置柱状图宽度,避免重叠 bar_width = 0.35 # 绘制分组柱状图,调整x轴位置区分两组 plt.bar(x - bar_width/2, pvgis_data, bar_width, label="PVGIS Generated") plt.bar(x + bar_width/2, pvoutput_data, bar_width, label="PVOUTPUT Generated") # 设置图表属性 plt.xlabel("Month") plt.ylabel("Generated (KWh)") plt.title("不同来源月发电量对比") plt.grid() plt.margins(x=0) plt.ticklabel_format(useOffset=False, axis="y", style="plain") plt.legend() # 放到绘图之后,才能获取图例标签 plt.show() plt.close()
补充说明
你之前尝试重新索引、将Month设为索引没用,是因为根本问题不是索引的问题,而是你错误地用列的取值去当列名索引DataFrame。只要直接取出列的数值用于绘图,就能解决KeyError。
内容的提问来源于stack exchange,提问作者Nnaobi
相关产品推荐
相关产品推荐

