Skip to content
Advertisement

How to reverse Label Encoder from sklearn for multiple columns?

I would like to use the inverse_transform function for LabelEncoder on multiple columns.

This is the code I use for more than one columns when applying LabelEncoder on a dataframe:

JavaScript

Is there a way to modify the code and change it so that it be used to inverse the labels from the encoder?

Thanks

Advertisement

Answer

In order to inverse transform the data you need to remember the encoders that were used to transform every column. A possible way to do this is to save the LabelEncoders in a dict inside your object. The way it would work:

  • when you call fit the encoders for every column are fit and saved
  • when you call transform they get used to transform data
  • when you call inverse_transform they get used to do the inverse transformation

Example code:

JavaScript

You can then use it like this:

JavaScript

There could be a separate implementation of fit_transform that would call the same method of LabelEncoders. Just make sure to keep the encoders around for when you need the inverse transformation.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement