Sklearn LabelEncoder throws TypeError in sort

I am studying computer training using the Kaggle Titanic dataset. I am using LabelEncoder from sklearn to convert text data to numeric labels. The following code is great for "Sex", but not for "Sent."

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

This is the error I received

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'

Description of dataset

+5
source share
2 answers

I decided it myself. The problem was that the particular function had NaN values. Replacing it with a numerical value, it still gives an error, because it has different data types. So I replaced it with a character value

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

, Pandas Dataframe. . .

def encoder(data):
'''Map the categorical variables to numbers to work with scikit learn'''
for col in data.columns:
    if data.dtypes[col] == "object":
        le = preprocessing.LabelEncoder()
        le.fit(data[col])
        data[col] = le.transform(data[col])
return data
+3

Source: https://habr.com/ru/post/1677079/


All Articles