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

如何筛选data_type=object的列?需调整代码指定该类列为categorical_features

筛选DataFrame中数据类型为object的列作为分类特征

直接用select_dtypes()方法就能精准筛选出数据类型为object的列,替换你原来的categorical_features赋值语句即可:

修改后的完整代码

from sklearn.preprocessing import LabelEncoder

encoder = LabelEncoder()
# 仅选取数据类型为object的列
categorical_features = df.select_dtypes(include=['object']).columns.tolist()
for col in categorical_features:
    # 注意:LabelEncoder不支持含缺失值的列,若数据有缺失需先处理(比如df[col].fillna('Unknown'))
    df[col] = encoder.fit_transform(df[col])
df.head(20)

补充说明

  • 如果你的数据里还有category类型的分类列需要一并处理,可以把include参数改成['object', 'category']
  • 运行前确认目标列没有缺失值,否则LabelEncoder会抛出错误,可提前用填充或删除缺失值的方式处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:05:28