Sklearn LabelEncoder在sort中抛出TypeError

Bha*_*avi 7 machine-learning scikit-learn sklearn-pandas

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

encoder = preprocessing.LabelEncoder()
features["Sex"] = encoder.fit_transform(features["Sex"])
features["Embarked"] = encoder.fit_transform(features["Embarked"])
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

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'
Run Code Online (Sandbox Code Playgroud)

数据集的描述

Bha*_*avi 18

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

 features["Embarked"] = encoder.fit_transform(features["Embarked"].fillna('0'))
Run Code Online (Sandbox Code Playgroud)