Replace specific values in a column via a mapping, leaving all other values unchanged. By hand, mapping.get(v, v) returns the mapped value or the original. With pandas, Series.replace(dict) does the same in one call.

By hand

With pandas

df['x'].replace(mapping) replaces 1→10 and 3→30, leaving 2 and 4 intact. The dtype stays int64 because all replacements and originals are integers.

naive.py
values = [1, 2, 3, 2, 4]
mapping = {1: 10, 3: 30}
result = []
for v in values:
    result.append(mapping.get(v, v))
print('RESULT:', result)
library.py
import pandas as pd
from dalib.display import set_display
set_display()

values = [1, 2, 3, 2, 4]
mapping = {1: 10, 3: 30}
df = pd.DataFrame({'x': values})
result = df['x'].replace(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: [10, 2, 30, 2, 4]
dtype: int64
RESULT: [10, 2, 30, 2, 4]

Implementation notes

  • Key contrast with .map: Series.replace(dict) leaves unmapped values unchanged; Series.map(dict) yields NaN for any key not in the mapping. Use .replace when you want partial substitution.
  • replace also accepts lists: df['x'].replace([1, 3], [10, 30]) is equivalent to the dict form above.
  • Cross-reference: map-values (this chapter) for the NaN-for-unmapped alternative using Series.map.