Sklearn LabelEncoder引发TypeError排序 [英] Sklearn LabelEncoder throws TypeError in sort

查看:189
本文介绍了Sklearn LabelEncoder引发TypeError排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用来自Kaggle的Titanic数据集学习机器学习.我正在使用sklearn的LabelEncoder将文本数据转换为数字标签.以下代码适用于性别",但不适用于禁运".

I am learning machine learning using Titanic dataset from Kaggle. I am using LabelEncoder of sklearn to transform text data to numeric labels. The following code works fine for "Sex" but not for "Embarked".

encoder = preprocessing.LabelEncoder()
features["Sex"] = encoder.fit_transform(features["Sex"])
features["Embarked"] = encoder.fit_transform(features["Embarked"])

这是我得到的错误

Traceback (most recent call last):
  File "../src/script.py", line 20, in <module>
    features["Embarked"] = encoder.fit_transform(features["Embarked"])
  File "/opt/conda/lib/python3.6/site-packages/sklearn/preprocessing/label.py", line 131, in fit_transform
    self.classes_, y = np.unique(y, return_inverse=True)
  File "/opt/conda/lib/python3.6/site-packages/numpy/lib/arraysetops.py", line 211, in unique
    perm = ar.argsort(kind='mergesort' if return_index else 'quicksort')
TypeError: '>' not supported between instances of 'str' and 'float'

推荐答案

我自己解决了这个问题.问题在于特定功能具有NaN值.用数值替换它仍然会引发错误,因为它具有不同的数据类型.所以我用一个字符值代替了它

I solved it myself. The problem was that the particular feature had NaN values. Replacing it with a numerical value it will still throw an error since it is of different datatypes. So I replaced it with a character value

 features["Embarked"] = encoder.fit_transform(features["Embarked"].fillna('0'))

这篇关于Sklearn LabelEncoder引发TypeError排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆