I am creating a dummy data set by using list and using the zip function.
city = ['London','Paris','New York ']
continent = ['Europe', 'Europe' ,'North America']
data = list(zip(city, continent))
data
Output
[('London', 'Europe'), ('Paris', 'Europe'), ('New York ', 'North America')]
Converting the data set into data frame
import pandas as pd
from sklearn.preprocessing import LabelEncoder
labelencoder=LabelEncoder()
df= pd.DataFrame(data, columns=['city', 'continent'])
df
df['label'] = labelencoder.fit_transform(df['city'])
df
City Continent
London Europe
Paris Europe
New York North America
You need to use fit_transform to fit the encoder and then transform the data. This will encode the labels as you want and will not re-fit the encoder.
Output
City Continent label
London Europe 0
Paris Europe 2
New York North America 1