0
0
Data Analysis Pythondata~5 mins

map() for element-wise mapping in Data Analysis Python

Choose your learning style9 modes available
Introduction

The map() function helps you change or replace each item in a list or column easily. It works like a translator that changes every word in a sentence.

You want to change all the colors in a list from names to codes.
You need to replace survey answers like 'Yes' and 'No' with numbers 1 and 0.
You want to clean data by fixing typos in a column of names.
You want to convert a list of country codes to full country names.
You want to apply a small function to each item in a list or column.
Syntax
Data Analysis Python
new_series = original_series.map(mapping_dict_or_function)

You can use a dictionary to replace values or a function to transform them.

If a value is not found in the dictionary, it becomes NaN by default.

Examples
This replaces 'cat' with 'kitten' and 'dog' with 'puppy'. 'bird' becomes NaN because it is not in the dictionary.
Data Analysis Python
import pandas as pd

s = pd.Series(['cat', 'dog', 'bird'])
mapping = {'cat': 'kitten', 'dog': 'puppy'}
new_s = s.map(mapping)
print(new_s)
This multiplies each number by 10 using a function.
Data Analysis Python
import pandas as pd

s = pd.Series([1, 2, 3, 4])
new_s = s.map(lambda x: x * 10)
print(new_s)
Sample Program

This program changes 'Yes' to 1 and 'No' to 0. 'Maybe' is not in the dictionary, so it becomes NaN.

Data Analysis Python
import pandas as pd

# Original data: survey answers
answers = pd.Series(['Yes', 'No', 'Yes', 'No', 'Maybe'])

# Mapping dictionary to convert answers to numbers
mapping = {'Yes': 1, 'No': 0}

# Use map() to replace answers
numeric_answers = answers.map(mapping)

print('Original answers:')
print(answers)
print('\nMapped numeric answers:')
print(numeric_answers)
OutputSuccess
Important Notes

If you want to keep original values when no match is found, use fillna() after map().

Using a function with map() is helpful for custom transformations.

Summary

map() changes each item in a list or column based on a dictionary or function.

Unmatched items become NaN by default when using a dictionary.

It is a simple way to clean or convert data step-by-step.