map()
map converts each value in a Series using a dictionary or a function.
In this page:
Syntax
df["column"].map({"old": "new"})
df["column"].map(function_name)
map()
Series.map accepts a dict, a Series or a function. With a dict, unmatched values become NaN. It is perfect for recoding categories such as turning "M" and "F" into full words.
Note:
map with a dict is often the fastest way to recode a column.
Example: map()
import pandas as pd
s = pd.Series(["M", "F", "M", "X"])
print(s.map({"M": "Male", "F": "Female"}))
print(pd.Series([1, 2, 3]).map(lambda x: x * 10))
# Output:
# 0 Male
# 1 Female
# 2 Male
# 3 NaN
# dtype: object
# 0 10
# 1 20
# 2 30
# dtype: int64
Related Topics
Common Mistakes
- Expecting unmatched keys to stay unchanged
- Using map on a whole DataFrame
- Forgetting it returns a new Series
Chapter Summary
- map accepts dict, Series or function
- Unmatched values become NaN
- It works on a Series
- Ideal for recoding
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: