Map class-name strings to integer codes using sorted unique order: build sorted(set(labels)) → dict mapping each class to its index → encode each label via lookup loop. Library: sklearn.preprocessing.LabelEncoder() .fit_transform(labels) assigns codes in sorted alphabetical order, matching the naive approach exactly. RESULT: integer code list.

By hand

With scikit-learn

LabelEncoder().fit_transform(labels) returns an integer array; .tolist() converts it. classes_ shows the sorted alphabet used for the mapping.

naive.py
labels = ['cat', 'dog', 'bird', 'cat', 'bird', 'dog', 'cat']
unique = sorted(set(labels))
code_map = {}
for i in range(len(unique)):
    code_map[unique[i]] = i
encoded = []
for lbl in labels:
    encoded.append(code_map[lbl])
print('RESULT:', encoded)
library.py
from sklearn.preprocessing import LabelEncoder
from dalib.display import set_display
set_display()

labels = ['cat', 'dog', 'bird', 'cat', 'bird', 'dog', 'cat']
le = LabelEncoder()
encoded = le.fit_transform(labels).tolist()
print('classes:', le.classes_.tolist())
print('RESULT:', encoded)
classes: ['bird', 'cat', 'dog']
RESULT: [1, 2, 0, 1, 0, 2, 1]

Implementation notes

  • LabelEncoder assigns codes in sorted (alphabetical) order — not insertion order. sorted(set(labels)) in the naive code reproduces this exactly.
  • set ordering is hash-based and NOT deterministic; the sorted() call is required for parity.
  • LabelEncoder is for target labels (y). For input features (X) containing categorical strings, use OrdinalEncoder (single column) or OneHotEncoder (multiple columns) instead.
  • Cross-reference: label-encode (data-cleaning) uses the same sorted-order convention via pandas cat.codes; both sklearn and pandas sort before assigning codes.