python - 使用 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''
有谁知道如何帮助我解决这个问题?谢谢
解决方案
此行正在转换为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)
推荐阅读
- r - 将最初以字符类型的日期转换为日期
- c# - 无法通过 HttpWebRequest C# 发送 okta 推送身份验证(使用 API)
- c# - 如何为任何控件提供可见性变化的滑动动画
- asp.net-core - ASP.NET Core WebApi EF:向用户添加角色
- java - 使用本机查询 Spring Boot 2 更新
- unit-testing - 找不到 SpringJUnit4ClassRunner.runleaf 方法
- python - 将特定文件从一个目录复制到另一个附加它的基本目录名称
- visual-studio - VSTS REST Api 创建任务
- python - 无法安装 setuptools
- javascript - 在 JSON 数组上应用多个过滤器时,只有第一个过滤器有效