Error "could not convert string to float" while running randomForest model in Python




While trying to run a randomForest model on a dataset in Python, I encountered an error saying

ValueError: could not convert string to float: source_class

where source_class is a column in my dataframe.

Why is this error coming and what is the solution?



Hi @adityashrm21,

Try to convert those strings into numeric classes. How? Please find below the code for the same -

from sklearn import preprocessing
def convert(data):
    number = preprocessing.LabelEncoder()
    data['Employer_Name'] = number.fit_transform(data.Employer_Name)
    data['Source'] = number.fit_transform(data.Source)
    return data


After this try running RF. Hope it will solve your problem. For any other modelling help refer here. It’s my github link.



I need to re-transform one variable into the original categories and number.inverse_transform() isn’t working. What shall I do?


Hi @adityashrm21,

In that case I assume that you are able to run your random forest. So I don’t know how to do this by using function, but it can be done by following steps -

  • Make a array of transformed variable from original dataset and transformed dataset and put them in a data frame
  • Make them unique, so you will have a table which contains the original variable and the numeric value the got transformed
  • Merge it with the final dataset on numeric variable

Hope this helps.



from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(), y_train)

and now getting this error

ValueError Traceback (most recent call last)
in ()
1 from sklearn.tree import DecisionTreeClassifier
2 classifier = DecisionTreeClassifier()
----> 3, y_train)

E:\anacondaff\lib\site-packages\sklearn\tree\ in fit(self, X, y, sample_weight, check_input, X_idx_sorted)
788 sample_weight=sample_weight,
789 check_input=check_input,
–> 790 X_idx_sorted=X_idx_sorted)
791 return self

E:\anacondaff\lib\site-packages\sklearn\tree\ in fit(self, X, y, sample_weight, check_input, X_idx_sorted)
114 random_state = check_random_state(self.random_state)
115 if check_input:
–> 116 X = check_array(X, dtype=DTYPE, accept_sparse=“csc”)
117 y = check_array(y, ensure_2d=False, dtype=None)
118 if issparse(X):

E:\anacondaff\lib\site-packages\sklearn\utils\ in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
431 force_all_finite)
432 else:
–> 433 array = np.array(array, dtype=dtype, order=order, copy=copy)
435 if ensure_2d:

ValueError: could not convert string to float: ‘unknown’


Hi @urvashi51,

Your data might have categorical variables. A decision tree cannot deal with categorical variables so you must convert the variables into numbers (one-hot encoding or label encoding)