What is the map method in pandas?

The map method in pandas maps values from one series to another based on a common column. Mapping is based on values within a series.

Since mapping is one-to-one, the series must have only unique values. An error will occur otherwise.

The illustration below shows how the map function works:

How does map method work

Syntax

The map method has the following syntax:

Series.map(arg, na_action=None)

Parameters

The map method takes two parameters:

  • arg: An object such as a dictionary, series, or function that determines the mapping.
  • na_action: Determines how to deal with NaN values. It can take two forms; by default, it is None. If it is ignore, mapping is not applied to NaN values.

map accepts values as dictionaries in the first parameter. If a value is not found in the dictionary, it is mapped to NaN.

Only the first parameter is compulsory.

Return value

The map function returns a series with the mappings incorporated.

Example

The code snippet below shows how we can use the map function in pandas:

import pandas as pd
import numpy as np
s = pd.Series(['cat', 'dog', np.nan, 'rabbit'])
print("Original Series")
print(s)
print('\n')
print("Mapping onto a dictiorary")
print(s.map({'cat': 'kitten', 'dog': 'puppy'}))
print('\n')
print("We can also map to a function")
print(s.map('I am a {}'.format))
print('\n')
print("Use the na_action parameter to avoid mapping NaN")
print(s.map('I am a {}'.format, na_action='ignore'))

Free Resources

HowDev By Educative. Copyright ©2025 Educative, Inc. All rights reserved