Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
pandas

What is the map method in pandas?

Hassaan Waqar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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'))

RELATED TAGS

python
pandas

CONTRIBUTOR

Hassaan Waqar
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring