Translate each code in a list to its label by looping over a dict. With pandas, Series.map(dict) applies the same elementwise lookup to an entire column in one call, returning a new Series of labels.

By hand

With pandas

df['code'].map(mapping) applies the dict lookup to every element of the column and returns a Series of translated labels. The snapshot shows the index, values, and dtype of the result.

naive.py
codes = ['A', 'B', 'A', 'C', 'B']
mapping = {'A': 'alpha', 'B': 'beta', 'C': 'gamma'}
labels = []
for code in codes:
    labels.append(mapping[code])
print('RESULT:', labels)
library.py
import pandas as pd
from dalib.display import set_display
set_display()

codes = ['A', 'B', 'A', 'C', 'B']
mapping = {'A': 'alpha', 'B': 'beta', 'C': 'gamma'}
df = pd.DataFrame({'code': codes})
labels = df['code'].map(mapping)
print('index:', labels.index.tolist())
print('values:', labels.tolist())
print('dtype:', labels.dtype)
print('RESULT:', labels.tolist())
index: [0, 1, 2, 3, 4]
values: ['alpha', 'beta', 'alpha', 'gamma', 'beta']
dtype: object
RESULT: ['alpha', 'beta', 'alpha', 'gamma', 'beta']

Implementation notes

  • .map(dict) returns NaN for any value not found in the dict. If every code is guaranteed to be in the mapping, this matches the naive loop exactly. Use .map(dict).fillna('unknown') to handle missing keys with a default.
  • .map also accepts a function: df['code'].map(str.lower) applies str.lower elementwise. This is an elementwise API — each Python function call runs per element, not as a vectorized kernel like NumPy arithmetic.
  • The result dtype is object (pandas string) here because the values are strings. For numeric mappings the dtype would follow the mapped values.
  • Contrast with pd.merge: .map is for simple key→value enrichment from a dict; merge is for joining two DataFrames that each have multiple columns. For a large label table, merge is more appropriate.
  • Cross-reference: lookup-enrich (python-data-basics) for the pure-Python dict-lookup version.