You need to enable JavaScript to run this app. pandas绘制箱线图指定thermal_template列时出现KeyError报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

pandas绘制箱线图指定thermal_template列时出现KeyError报错如何解决

问题描述

我有一个包含三列的 DataFrame,分别为 ID、thermal_template、lighting_density。我需要生成按 thermal_template 分组的水平箱线图,其中 y 轴为各类 thermal_template 取值,x 轴为 lighting_density 取值。

我使用的代码如下:

boxplot = result.boxplot(column='thermal_template', figsize=(18,8), rot = 90)

运行后触发报错:

KeyError: "None of [Index(['thermal_template'], dtype='object')] are in the [columns]"

我已确认 thermal_template 是数据集的有效列名,可复现问题的代码如下:

import pandas as pd
import matplotlib.pyplot as plt

d = {'ID': [1, 2, 3], 'thermal_template': ['Zone A', 'Zone A/B', 'Zone A/B'], 'lighting_density':[0.36, 0.88, 0.74 ]}
df = pd.DataFrame(data=d)
df

boxplot = df.boxplot(column='thermal_template')

解决方案

报错原因

  • pandas.DataFrame.boxplot 的 column 参数用于指定需要统计分布的数值列,by 参数才是指定分组依据的类别列的参数,你将分组列填到了数值列的参数位,才触发了参数匹配错误。
  • 你需要的水平箱线图需要额外设置 vert=False 参数(默认 vert=True 为垂直箱线图)。

修正后代码

import pandas as pd
import matplotlib.pyplot as plt

d = {'ID': [1, 2, 3], 'thermal_template': ['Zone A', 'Zone A/B', 'Zone A/B'], 'lighting_density':[0.36, 0.88, 0.74 ]}
df = pd.DataFrame(data=d)

# 正确配置参数
boxplot = df.boxplot(
    column='lighting_density',  # 要统计分布的数值列
    by='thermal_template',      # 分组依据的类别列
    vert=False,                 # 生成水平箱线图
    figsize=(18,8)
)
# 调整图表标题和坐标轴标注
plt.title('按thermal_template分组的lighting_density分布')
plt.suptitle('') # 移除pandas默认生成的分组提示标题
plt.xlabel('lighting_density')
plt.ylabel('thermal_template')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:42:03