首页 > 解决方案 > 使用 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''

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

标签: pythonnumpyscikit-learnlabel-encoding

解决方案


此行正在转换为bytes_编码器不支持的 numpy:

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

如果要转换为字符串,请更改'|S'str

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

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

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

推荐阅读