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

使用SelectFromModel做特征选择时出现KeyError:0问题求助

解决KeyError: 0问题(Selector Object特征选择)

错误根源

报错出现在print('- ' + feature_names[feature_list_index])行,核心问题是:

  • sfm.get_support(indices=True)返回的是特征在数据集中的整数位置索引(如0、1、2...)
  • 你的feature_names并非普通列表,而是pandas的Index或Series对象——这类对象用[]访问时遵循标签索引逻辑,而非位置索引。如果feature_names的标签不包含0(或不是连续整数),就会触发KeyError: 0。

你之前尝试的feature_list_index = defaultdict(list)完全没触碰到核心问题,因为错误根源不在循环变量本身,而在feature_names的访问方式。

修复方案

根据feature_names的实际类型,选择以下任意一种方法修复:

方法1:将feature_names转为普通列表

如果feature_names是从X_train的列名获取的,直接转成列表即可:

# 替换你获取feature_names的代码
feature_names = X_train.columns.tolist()

之后循环里的feature_names[feature_list_index]就能正常按整数位置访问。

方法2:用.iloc按位置访问(保留pandas对象)

如果需要保留feature_names为pandas的Index或Series类型,修改循环内的访问逻辑:

for feature_list_index in sfm.get_support(indices=True):
    print('- ' + feature_names.iloc[feature_list_index])

.iloc是pandas专门用于按整数位置访问的方法,刚好匹配sfm.get_support(indices=True)返回的索引格式。

验证

修改后重新运行代码,即可正常打印选中的特征名称,不再触发KeyError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:50:06