Is there any way to reverse categorical value to original string or text value?

Viewed 1088

I have applied below is the data frame

   cc  temp  
0  US  37.0     
1  CA  12.0     
2  US  35.0     
3  AU  20.0     

Now convert into category using

df =  df.cc.cat.codes

I'm getting this as output

   cc  temp  
0  2  37.0     
1  1  12.0     
2  2  35.0     
3  0  20.0     

My requirement is that how can I reverse it as origin any idea?

1 Answers

You could use LabelEncoder from sklearn.preprocessing, which offers a similar functionality to what you've done.

Here's how to do it with your dataframe:

# Assuming you've created the dataframe already

from sklearn.preprocessing import LabelEncoder

le = LabelEncoder()

# Transforming categorical variable to label encoded form
df['cc'] = le.fit_transform(df['cc'])

# Converting back from label encoded form to labels
df['cc'] = le.inverse_transform(df['cc'])

You can read about label encoder and scikit-learn's implementation at https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html.

Might also help to read about other forms of encoding categorical variables such as one hot encoding and target encoding, and which to use where.

Related