# Replacing the feature variables with encoded variables

I have several nominal variables which I've encoded using the LabelEncoder() function. Now I want to replace the encoded values in the place of the raw datas of the features in the dataframe. I tried df.replace() but no luck. Below is the code snippet.

nominal_values = [
'HouseStyle','ExterQual','BsmtQual','BsmtExposure','BsmtFinType1',
'KitchenQual','GarageType','GarageFinish','GarageQual','GarageCond']


One of the column "KitchenQual" has values as follows:

{kitchenqual :['Ex','Gd','TA','Fa','Po']} representing "Excellent","Good","Typical/Average","Fair","Poor" respectively.

Another Feature "BsmtFinType1" has values as follows:

{BsmtFinType1: ['GLQ','ALQ','BLQ','Rec','LwQ','Unf','NA']} represeting

"Good Living Quarters","Average Liv. Quat.","Below Avg.Liv.Quat,","Avg. rec room", "Low Quality", "Unfinished","No Basement" respectively.

from sklearn.preprocessing import LabelEncoder

lbe = LabelEncoder()
for noms in nominal_values:
encode = lbe.fit_transform(cat_var[noms])
cat_var.replace(to_replace=cat_var[noms],
value=pd.Series(encode),inplace=True)


I used pd.Series(encode) since the replace function will support only one of the following data structures

• Scalar
• dict
• Series
• Hi. If you want help with code, you should post a minimal working example illustrating your problem in as few lines of code as possible, not just a snippet. Dec 29, 2017 at 7:42
• Hi @Miguel I have updated the question with the sample of feature values available for the same in the dataset. Please go through and guide me in where am I missing. Sorry for not giving out this information beforehand Dec 31, 2017 at 11:35
• What about cat_var[noms] = encode (or cat_var[noms] = pd.Series(encode) but I'm sure you just just use the list instead of casting as a Series)
– Dan
Jan 4, 2018 at 18:47

cat_var.replace(to_replace=cat_var[noms].tolist(),value=encode,inplace=True)
Instead of converting encoded values to series, convert series to list using tolist().
• I dived deeper into this and found that at backend it basically uses np.unique to return the encoded values. [link] docs.scipy.org/doc/numpy-1.13.0/reference/generated/… This function,(np.unique), by default, sorts the input array so in your example you will always get Ex:0, Fa:1 etc. The solution (you know) is to sort the list in reverse order. Jan 5, 2018 at 11:28