You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python绘制seaborn heatmap遇KeyError: Interval问题求助

问题:绘制空气化合物与气象因子热力图时触发KeyError

我正在完成作业任务:可视化空气化合物与气象因子的关系,需为每种化合物分别绘制散点图和热力图(共2个散点图、2个热力图),热力图要求用pd.cut创建分箱。编写代码后执行时出现KeyError: Interval(6.3, 8.4, closed='right')错误,尝试不同分箱方法仍无法解决。

原代码

#// BEGIN_TODO [EDA_relationship] (5 points)
sns.scatterplot(x=df_data[chosen_weather_factor], y=df_data[compound1])
plt.xlabel('Wind speed')
plt.ylabel(compound1)
plt.show()

sns.scatterplot(x=df_data[chosen_weather_factor], y=df_data[compound2])
plt.xlabel('Wind speed')
plt.ylabel(compound2)
plt.show()

bins = pd.cut(df_data[chosen_weather_factor], 10)
grouped_data = df_data.groupby(bins)[compound1].mean().reset_index()
heatmap_data = grouped_data.pivot(index='wind_speed', columns=bins, values=compound1)
sns.heatmap(heatmap_data, cmap='YlOrRd')
plt.xlabel(chosen_weather_factor)
plt.ylabel(compound1)
plt.title(f"Heatmap for {compound1} with respect to {chosen_weather_factor}")
plt.show()

bins = pd.cut(df_data[chosen_weather_factor], 10)
heatmap_data = df_data.groupby([bins])[compound2].mean().reset_index()
heatmap_data = heatmap_data.pivot(index='wind_speed', columns=bins, values=compound2)
sns.heatmap(heatmap_data, cmap='YlOrRd')
plt.xlabel('Wind speed')
plt.ylabel(compound2)
plt.show()

错误信息

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3079             try:
-> 3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: Interval(6.3, 8.4, closed='right')

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
<ipython-input-45-11233484bf6a> in <module>
     12 bins = pd.cut(df_data[chosen_weather_factor], 10)
     13 grouped_data = df_data.groupby(bins)[compound1].mean().reset_index()
---&gt; 14 heatmap_data = grouped_data.pivot(index='wind_speed', columns=bins, values=compound1)
     15 sns.heatmap(heatmap_data, cmap='YlOrRd')
     16 plt.xlabel(chosen_weather_factor)

~\anaconda3\lib\site-packages\pandas\core\frame.py in pivot(self, index, columns, values)
   6877         from pandas.core.reshape.pivot import pivot
   6878 
-> 6879         return pivot(self, index=index, columns=columns, values=values)
   6880 
   6881     _shared_docs[

~\anaconda3\lib\site-packages\pandas\core\reshape\pivot.py in pivot(data, index, columns, values)
    447             index = [data[idx] for idx in index]
    448 
-> 449         data_columns = [data[col] for col in columns]
    450         index.extend(data_columns)
    451         index = MultiIndex.from_arrays(index)

~\anaconda3\lib\site-packages\pandas\core\reshape\pivot.py in <listcomp>(.0)
    447             index = [data[idx] for idx in index]
    448 
-> 449         data_columns = [data[col] for col in columns]
    450         index.extend(data_columns)
    451         index = MultiIndex.from_arrays(index)

~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   3022             if self.columns.nlevels > 1:
   3023                 return self._getitem_multilevel(key)
-> 3024             indexer = self.columns.get_loc(key)
   3025             if is_integer(indexer):
   3026                 indexer = [indexer]

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:
-> 3082                 raise KeyError(key) from err
   3083 
   3084         if tolerance is not None:

KeyError: Interval(6.3, 8.4, closed='right')

错误原因

  1. pivot参数误用:grouped_data是分组后的结果,列名是原气象因子列和化合物列,但你在pivot时传入columns=bins——bins是整个数据集的分箱Series,并非grouped_data的列名,因此找不到对应列导致KeyError。
  2. index='wind_speed'无意义:分组后的数据中不存在'wind_speed'列,分组依据是分箱区间,不是原始风速值,这里属于参数错误。
  3. 热力图数据结构错误:分组求均值后已经是分箱区间与均值的一一对应关系,不需要用pivot转换,直接调整格式即可。

修正后的代码

方法一:调整分组后的数据格式

#// BEGIN_TODO [EDA_relationship] (5 points)
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# 绘制散点图
sns.scatterplot(x=df_data[chosen_weather_factor], y=df_data[compound1])
plt.xlabel('Wind speed')
plt.ylabel(compound1)
plt.show()

sns.scatterplot(x=df_data[chosen_weather_factor], y=df_data[compound2])
plt.xlabel('Wind speed')
plt.ylabel(compound2)
plt.show()

# 绘制compound1的热力图
bins = pd.cut(df_data[chosen_weather_factor], 10)
# 分组求均值,并重命名分箱列便于后续操作
grouped_data = df_data.groupby(bins, as_index=False)[compound1].mean()
grouped_data.rename(columns={chosen_weather_factor: 'weather_bins'}, inplace=True)
# 转换为热力图需要的矩阵格式
heatmap_data = grouped_data.pivot(columns='weather_bins', values=compound1).T
sns.heatmap(heatmap_data, cmap='YlOrRd', annot=True)
plt.xlabel(compound1)
plt.ylabel(chosen_weather_factor)
plt.title(f"Heatmap for {compound1} with respect to {chosen_weather_factor}")
plt.show()

# 绘制compound2的热力图
bins = pd.cut(df_data[chosen_weather_factor], 10)
grouped_data = df_data.groupby(bins, as_index=False)[compound2].mean()
grouped_data.rename(columns={chosen_weather_factor: 'weather_bins'}, inplace=True)
heatmap_data = grouped_data.pivot(columns='weather_bins', values=compound2).T
sns.heatmap(heatmap_data, cmap='YlOrRd', annot=True)
plt.xlabel(compound2)
plt.ylabel('Wind speed')
plt.title(f"Heatmap for {compound2} with respect to Wind speed")
plt.show()

方法二:用pivot_table简化实现

#// BEGIN_TODO [EDA_relationship] (5 points)
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# 绘制散点图
sns.scatterplot(x=df_data[chosen_weather_factor], y=df_data[compound1])
plt.xlabel('Wind speed')
plt.ylabel(compound1)
plt.show()

sns.scatterplot(x=df_data[chosen_weather_factor], y=df_data[compound2])
plt.xlabel('Wind speed')
plt.ylabel(compound2)
plt.show()

# compound1热力图
heatmap_data = df_data.pivot_table(
    index=pd.cut(df_data[chosen_weather_factor], 10),
    values=compound1,
    aggfunc='mean'
)
sns.heatmap(heatmap_data, cmap='YlOrRd', annot=True)
plt.xlabel(compound1)
plt.ylabel(chosen_weather_factor)
plt.title(f"Heatmap for {compound1} with respect to {chosen_weather_factor}")
plt.show()

# compound2热力图
heatmap_data = df_data.pivot_table(
    index=pd.cut(df_data[chosen_weather_factor], 10),
    values=compound2,
    aggfunc='mean'
)
sns.heatmap(heatmap_data, cmap='YlOrRd', annot=True)
plt.xlabel(compound2)
plt.ylabel('Wind speed')
plt.title(f"Heatmap for {compound2} with respect to Wind speed")
plt.show()

内容的提问来源于stack exchange,提问作者Queirbeer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:09:53