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

在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拟合

修复步骤

  1. 替换独立if为elif:确保每列仅被处理一次,避免类型转换后的重复操作
  2. 移除全空列:提前删除所有值均为NaN的列,避免无效特征输入
  3. 优化int列填充后的类型处理:填充均值后可选择保持int类型
  4. 增加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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:01:17