使用 LabelEncoder 转换数据

问题描述

我编写了这个函数来使用 LabelEncoder 转换分类特征

#convert columns to dummies with LabelEncoder
cols = ['ToolType','TestType','BatteryType']
#apply ene hot encoder
le = LabelEncoder()
for col in cols:
    data[col] = data[col].astype('|S') #convert object to str type before apply label encoder
    le.fit(ravel(data[col]))
    data[col] = le.transform(ravel(data[col]))

那些列中有空值,但有这样的错误

TypeError: ufunc 'isnan' not supported for the input types,and the inputs Could not be safely coerced to any supported types according to the casting rule ''safe''

有谁知道如何帮助我解决这个问题?谢谢

解决方法

这一行正在转换为编码器不支持的 numpy bytes_

data[col] = data[col].astype('|S')

如果要转成字符串,把'|S'改成str

data[col] = data[col].astype(str)

作为旁注,您可以使用 apply()fit_transform 将循环减少到一行:

df[cols] = df[cols].astype(str).apply(le.fit_transform)