Remap values in pandas column with a dict, preserve NaNs
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Remapping a pandas column with a dictionary is easy until missing values enter the picture. The subtle part is not preserving existing NaN values, because pandas already does that well. The real subtlety is deciding what should happen to non-null values that are not present in the mapping dictionary.
map Preserves Existing NaN Values
The simplest remapping tool is Series.map:
Output:
Notice the two different reasons for NaN in the result:
- the original third row was already missing
- the value
"hold"was not found in the dictionary
That is the key behavior of map. It preserves existing NaN values, but it also turns unmapped non-null values into NaN.
Keep Unmapped Values Instead of Replacing Them with NaN
If you want to remap only known values and leave everything else unchanged, combine map with fillna:
Output:
This pattern is often the most useful answer in real data-cleaning work because it preserves both original missing values and original unmapped categories.
replace Is Sometimes the Better Tool
For straightforward value substitution, replace is even more direct:
Output:
Unlike map, replace changes only matching values and leaves everything else alone. That makes it a strong choice when your mapping is partial by design.
Another practical difference is intent. When another developer reads replace(mapping), the code clearly says "swap known labels." When they read map(mapping), it often implies a stricter lookup where missing keys may be meaningful. That small readability difference is useful in data-cleaning pipelines.
Apply the Remap Back to the DataFrame
Once the logic is correct, write it back explicitly:
If the column uses pandas' nullable dtypes or categorical data, it is still worth checking the final dtype after transformation. Some remapping operations can widen the dtype to object when the new values do not fit the original representation cleanly.
Choose the Method Based on Intent
Use:
- '
mapwhen you want a strict mapping and are comfortable with unknown values becomingNaN' - '
map(...).fillna(original_series)when you want mapped values plus untouched unknowns' - '
replacewhen you want partial substitution and existing unknowns should remain unchanged'
That choice matters more than memorizing one function name.
Common Pitfalls
- Assuming
mapwill leave unmapped non-null values unchanged. - Forgetting that
NaNin the result may come from either original missing values or missing dictionary keys. - Using
applywith a custom lambda for a simple dictionary substitution thatmaporreplacealready handles efficiently. - Overwriting the original column before checking how unmapped categories behaved.
- Ignoring dtype changes after remapping, especially with categorical or nullable columns.
Summary
- pandas
mapalready preserves existingNaNvalues. - Unmapped non-null values become
NaNwhen you usemap. - Use
map(...).fillna(original_series)if unknown values should remain unchanged. - Use
replacewhen you want partial substitution without turning unknown values into missing values. - The right tool depends on whether unmapped values should disappear or survive.
Related reading
- Remove duplicates by columns A, keeping the row with the highest value in column B
- Remove pandas rows with duplicate indices
- Remove rows with all or some NAs (missing values) in data.frame
- Remove unwanted parts from strings in a column
- Remove __pycache__ folders and .pyc files from Python project
- Remove a prefix from a string
- Removing Conda environment
- Removing index column in pandas when reading a csv
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.