Python按性别和年龄区间绘制柱状图遇KeyError问题求助
KeyError问题排查与解决
核心原因
你的代码触发KeyError,本质是统计结果的索引和你定义的age_range_labels不匹配,可能是以下两种情况:
- 没有先将原始年龄数据分组到指定区间,直接对整行数据做
value_counts(),统计结果的索引根本不是年龄区间; - 即使有现成的
age_range列,某些区间在数据中无对应记录,value_counts()不会生成这些索引,用[age_range_labels]直接索引就会报错。
针对性解决方法
情况1:原始数据是单个年龄数值(如age列存45、62这类数字)
需要先把年龄分到你指定的区间,再统计数量:
import pandas as pd import numpy as np import matplotlib.pyplot as plt def create_bar_plot_by_sex(covid19_data, age_ranges): # 生成区间标签和分组边界 age_range_labels = [f"{s}-{e}" for s, e in age_ranges] bins = [x for r in age_ranges for x in r] # 给数据新增年龄区间列 covid19_data['age_range'] = pd.cut( covid19_data['age'], bins=bins, labels=age_range_labels, include_lowest=True # 确保左边界包含在内 ) # 按性别+年龄区间分组统计,缺失的区间补0 group_counts = covid19_data.groupby(['sex', 'age_range']).size().unstack(fill_value=0) counts_male = group_counts.loc['male'] counts_female = group_counts.loc['female'] # 绘图部分 fig, ax = plt.subplots(figsize=(20, 10)) index = np.arange(len(age_ranges)) bar_width = 0.35 opacity = 0.8 rects1 = plt.bar(index, counts_male, bar_width, alpha=opacity, color='b', label='Male') rects2 = plt.bar(index + bar_width, counts_female, bar_width, alpha=opacity, color='g', label='Female') plt.xlabel('Age Range') plt.ylabel('Count') plt.title('Corona Cases per Age Group') plt.xticks(index + bar_width/2, [f"[{s},{e})" for s,e in age_ranges]) plt.legend() plt.tight_layout() return counts_female, counts_male cnts_f, cnts_m = create_bar_plot_by_sex(covid19_data, age_ranges)
情况2:数据已存在age_range列
只需修改统计逻辑,用reindex确保所有指定区间都被包含,缺失值补0:
import numpy as np import matplotlib.pyplot as plt def create_bar_plot_by_sex(covid19_data, age_ranges): age_range_labels = [f"{s}-{e}" for s, e in age_ranges] # 筛选女性数据并统计年龄区间,缺失区间补0 female_ages = covid19_data[covid19_data['sex']=="female"]['age_range'] counts_female = female_ages.value_counts().reindex(age_range_labels, fill_value=0) # 筛选男性数据并统计年龄区间,缺失区间补0 male_ages = covid19_data[covid19_data['sex']=='male']['age_range'] counts_male = male_ages.value_counts().reindex(age_range_labels, fill_value=0) # 绘图部分不变 fig, ax = plt.subplots(figsize=(20, 10)) index = np.arange(len(age_ranges)) bar_width = 0.35 opacity = 0.8 rects1 = plt.bar(index, counts_male, bar_width, alpha=opacity, color='b', label='Male') rects2 = plt.bar(index + bar_width, counts_female, bar_width, alpha=opacity, color='g', label='Female') plt.xlabel('Age Range') plt.ylabel('Count') plt.title('Corona Cases per Age Group') plt.xticks(index + bar_width/2, [f"[{s},{e})" for s,e in age_ranges]) plt.legend() plt.tight_layout() return counts_female, counts_male cnts_f, cnts_m = create_bar_plot_by_sex(covid19_data, age_ranges)
额外注意点
- 检查
sex列的取值大小写:如果数据中是Female/Male,而你代码里用的是female/male,会导致筛选不到数据,统计结果全为0; - 确保
age_range列的格式和你生成的age_range_labels完全一致(比如有没有空格、符号差异)。
内容的提问来源于stack exchange,提问作者kixx
相关产品推荐
相关产品推荐

