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

使用Python Matplotlib绘制分组均值图遇KeyError: 'Race'的解决方法

按种族分组的房贷均值可视化错误修复

错误原因

执行df.groupby("Race").mean()后,"Race"列会被设置为DataFrame的索引,不再是普通数据列,因此dfm["Race"]会触发KeyError。

修正方案

以下两种方法都可以实现X轴为种族、Y轴为房贷均值的可视化:

方法1:重置索引将Race恢复为列

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv(r'usa survey data edited.csv')
fig, ax = plt.subplots()
# 分组计算均值后,重置索引让Race回到列中
dfm = df.groupby("Race").mean().reset_index()
# 用柱状图展示分类数据(比折线图更合适)
ax.bar(dfm["Race"], dfm["Mortgage"])
# 旋转X轴标签避免重叠
plt.xticks(rotation=45)
plt.xlabel("种族")
plt.ylabel("房贷均值")
plt.title("不同种族的房贷均值统计")
plt.tight_layout()  # 自动调整布局防止标签被截断
plt.show()

方法2:直接使用分组后的索引作为X轴

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv(r'usa survey data edited.csv')
fig, ax = plt.subplots()
dfm = df.groupby("Race").mean()
# 分组后的索引就是Race,直接用dfm.index获取
ax.bar(dfm.index, dfm["Mortgage"])
plt.xticks(rotation=45)
plt.xlabel("种族")
plt.ylabel("房贷均值")
plt.title("不同种族的房贷均值统计")
plt.tight_layout()
plt.show()

额外说明

种族属于分类变量,使用柱状图比折线图更符合数据展示逻辑;如果坚持要用折线图,只需把代码中的ax.bar替换为ax.plot即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:20:14