在Jupyter Notebook做机器学习时遇特征数为0错误求解决
解决方案
错误原因分析
错误提示Found array with 0 feature(s) (shape=(10792, 0)) while a minimum of 1 is required本质是传入sklearn模型的数组特征数为0,结合你的代码,主要触发点有两个:
- 循环中使用独立
if判断,导致同一列被多次处理(比如int类型列填充均值后 dtype 变为float,进而触发float列的处理逻辑,若该列无有效数据会引发异常) - 存在完全为空的列(所有值都是NaN),导致
reshape(-1,1)后仍无法提供有效特征供IterativeImputer拟合
修复步骤
- 替换独立
if为elif:确保每列仅被处理一次,避免类型转换后的重复操作 - 移除全空列:提前删除所有值均为NaN的列,避免无效特征输入
- 优化int列填充后的类型处理:填充均值后可选择保持int类型
- 增加float列有效性检查:对全空的float列单独处理,避免
IterativeImputer报错
修改后的代码
from sklearn.experimental import enable_iterative_imputer from sklearn.impute import IterativeImputer import pandas as pd imp = IterativeImputer(random_state=42) date = pd.Timestamp('2200-01-01') # 删除所有全空的列 combi = combi.dropna(axis=1, how='all') for col in combi: if combi[col].dtype == "object": combi[col].fillna("not listed", inplace=True) elif combi[col].dtype == "int": # 填充均值后转回int类型(不需要可删除astype(int)) combi[col] = combi[col].fillna(combi[col].mean()).round().astype(int) elif combi[col].dtype == 'float': # 检查是否有非NaN值,避免全空列触发异常 if combi[col].notna().any(): combi[col] = imp.fit_transform(combi[col].values.reshape(-1,1)) else: # 全空float列用默认值填充,也可选择删除该列 combi[col].fillna(0, inplace=True) elif combi[col].dtype == "datetime64[ns]": combi[col].fillna(date, inplace=True) combi
额外说明
- 若不需要保留int类型,可将int列处理逻辑改回
combi[col].fillna(combi[col].mean(), inplace=True),但此时列类型会变为float - 若想保留全空列,可替换
dropna步骤为对全空列单独填充默认值,不使用IterativeImputer
内容的提问来源于stack exchange,提问作者Syed Faseeh Ul Hassan
相关产品推荐
相关产品推荐

