How to apply LabelEncoder for a specific column in Pandas dataframe How to apply LabelEncoder for a specific column in Pandas dataframe python-3.x python-3.x

How to apply LabelEncoder for a specific column in Pandas dataframe


You can try as following:

le = preprocessing.LabelEncoder()df['label'] = le.fit_transform(df.label.values)

Or following would work too:

df['label'] = le.fit_transform(df['label'])

It will replace original label values in dataframe with encoded labels.


You can also do:

from sklearn.preprocessing import LabelEncoderle = LabelEncoder()df.col_name= le.fit_transform(df.col_name.values)

where col_name = the feature that you want to label encode


 from sklearn.preprocessing import LabelEncoder le = LabelEncoder() X[:, 2] = le.fit_transform(X[:, 2]) 

this could be helpful if you want to change the particular column in your CSV data