Apply and Values
Replace Values
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
Loop over values, using mapping.get(v, v) to replace mapped values and
return the original v for everything else. The unmapped values (2 and 4)
pass through unchanged.
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)
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.
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)yieldsNaNfor any key not in the mapping. Use.replacewhen you want partial substitution. replacealso 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 usingSeries.map.