Remap a column of categorical codes to labels using a dict lookup per row. With pandas, Series.map(dict) does this in one call; keys absent from the mapping become NaN rather than raising an error.

By hand

With pandas

df['score'].map(mapping) replaces each element with the corresponding dict value. The snapshot shows dtype: object because the mapped labels are strings.

naive.py
scores = [1, 3, 2, 1, 3]
mapping = {1: 'low', 2: 'mid', 3: 'high'}
result = []
for s in scores:
    result.append(mapping[s])
print('RESULT:', result)
library.py
import pandas as pd
from dalib.display import set_display
set_display()

scores = [1, 3, 2, 1, 3]
mapping = {1: 'low', 2: 'mid', 3: 'high'}
df = pd.DataFrame({'score': scores})
result = df['score'].map(mapping)
print('index:', result.index.tolist())
print('values:', result.tolist())
print('dtype:', result.dtype)
print('RESULT:', result.tolist())
index: [0, 1, 2, 3, 4]
values: ['low', 'high', 'mid', 'low', 'high']
dtype: object
RESULT: ['low', 'high', 'mid', 'low', 'high']

Implementation notes

  • Keys not present in the mapping become NaN (the original value is NOT preserved). To leave unmapped values unchanged, use Series.replace(dict) instead.
  • Series.map also accepts a function: df['score'].map(str) converts each element to a string. This is the same elementwise API as Series.apply — each Python call runs per element.
  • map-lookup-column (ch05) uses .map for a join-like lookup (one column's codes resolve foreign-key labels). The API is identical; the distinction is conceptual — here we remap existing column values, there we enrich from a separate lookup table.
  • Cross-reference: dict-lookup-table (python-data-basics ch05) for the pure-Python dict-lookup version.