0
0
Pandasdata~5 mins

map() for element-wise transformation in Pandas

Choose your learning style9 modes available
Introduction

The map() function helps change each item in a list or column one by one. It makes it easy to update or replace values quickly.

You want to replace codes with full names, like 'NY' to 'New York'.
You need to apply a small calculation or change to each value in a column.
You want to convert categories to numbers for analysis.
You want to clean or fix typos in text data in a column.
Syntax
Pandas
Series.map(arg, na_action=None)

# arg can be a dict, function, or Series
# na_action='ignore' skips missing values

map() works on pandas Series (one column).

You can pass a dictionary to replace values, or a function to transform each value.

Examples
Replace 'cat' with 'kitten' and 'dog' with 'puppy'. 'bird' stays the same (becomes NaN).
Pandas
import pandas as pd
s = pd.Series(['cat', 'dog', 'bird'])
mapped = s.map({'cat': 'kitten', 'dog': 'puppy'})
Multiply each number by 10 using a function.
Pandas
s = pd.Series([1, 2, 3])
mapped = s.map(lambda x: x * 10)
Convert text to uppercase but keep None as is.
Pandas
s = pd.Series(['apple', None, 'banana'])
mapped = s.map(str.upper, na_action='ignore')
Sample Program

This program changes fruit names to their colors using map(). Fruits not in the map become NaN.

Pandas
import pandas as pd

# Create a simple data column
fruits = pd.Series(['apple', 'banana', 'cherry', 'date'])

# Map fruit names to colors
color_map = {'apple': 'red', 'banana': 'yellow', 'cherry': 'red'}

# Use map to replace fruit names with colors
fruit_colors = fruits.map(color_map)

print(fruit_colors)
OutputSuccess
Important Notes

If a value is not in the dictionary, map() returns NaN for that value.

Use na_action='ignore' to keep missing values unchanged when using a function.

Summary

map() changes each item in a pandas Series one by one.

You can use a dictionary or a function with map().

It is useful for replacing or transforming data quickly.