0PricingLogin
Pandas & NumPy Academy · Lesson

map() and applymap() for Element-Wise Operations

Apply a function to every element of a Series with map() and to every cell of a DataFrame with applymap().

Series.map() Overview

Series.map() applies a function, dictionary, or another Series to every element of a Series and returns a new Series. Unlike apply(), which can receive complex objects, map() always operates on individual scalar values. It is the standard tool for encoding categorical values, looking up labels from a mapping table, or applying a simple transformation element by element.

import pandas as pd

codes = pd.Series(['N', 'S', 'E', 'N', 'W'])
region_names = {'N': 'North', 'S': 'South', 'E': 'East', 'W': 'West'}

names = codes.map(region_names)
print(names)

map() with a Function

Pass a function (including a lambda) to map() when the transformation involves logic rather than a lookup table. The function receives one scalar at a time, so it cannot access other rows or columns. For a simple conditional label assignment, map() with a function is cleaner than a loop but slower than np.where() for large Series.

prices = pd.Series([5.0, 25.0, 80.0, 150.0])

category = prices.map(lambda p: 'budget' if p < 20 else 'mid' if p < 100 else 'premium')
print(category)

All lessons in this course

  1. apply() on Columns and Rows
  2. apply() with GroupBy
  3. map() and applymap() for Element-Wise Operations
  4. Method Chaining with pipe()
← Back to Pandas & NumPy Academy