← Back to Pandas Course | Chapter 6: Data Operations | Lesson 2 of 7

map()

map converts each value in a Series using a dictionary or a function.

In this page:

  1. map()
Syntax
python
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()

python
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
  1. Expecting unmatched keys to stay unchanged
  2. Using map on a whole DataFrame
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.