<code>map(function, iterable)</code>
Table of Contents
Table of Contents
Introduction
Python is a powerful programming language that offers a wide range of functions and modules to developers. One of the most commonly used functions in Python is map(). The map() function is used to apply a function to all the elements in an iterable and return an iterable map object. In this article, we will explore the basics of map(), apply(), and applymap() in Python.The Basics of map()
The map() function is used to apply a function to all the elements in an iterable. The syntax for the map() function is as follows:map(function, iterable)
The Basics of apply()
The apply() function is used to apply a function to a DataFrame in pandas. The syntax for the apply() function is as follows:df.apply(function)
The Basics of applymap()
The applymap() function is used to apply a function to each element in a DataFrame. The syntax for the applymap() function is as follows:df.applymap(function)
Examples of map(), apply(), and applymap()
Let's explore some examples of map(), apply(), and applymap() functions in Python.Example 1: Using the map() function
Suppose you have a list of numbers, and you want to add 5 to each element in the list. You can use the map() function to apply the function to each element in the list.numbers = [1, 2, 3, 4, 5]
def add_5(num):
return num + 5
result = map(add_5, numbers)
print(list(result))
[6, 7, 8, 9, 10]
Example 2: Using the apply() function
Suppose you have a DataFrame with three columns: 'name', 'age', and 'salary'. You want to add 500 to the salary of each employee.import pandas as pd
data = {'name': ['John', 'Jane', 'Mark'],
'age': [25, 30, 35],
'salary': [5000, 6000, 7000]}
df = pd.DataFrame(data)
def add_500(salary):
return salary + 500
df['salary'] = df['salary'].apply(add_500)
print(df)
name age salary
0 John 25 5500
1 Jane 30 6500
2 Mark 35 7500
Example 3: Using the applymap() function
Suppose you have a DataFrame with two columns: 'price' and 'quantity'. You want to calculate the total cost by multiplying the price and quantity of each item.data = {'price': [10, 20, 30],
'quantity': [2, 3, 4]}
df = pd.DataFrame(data)
def calculate_cost(price, quantity):
return price * quantity
df = df.applymap(calculate_cost)
print(df)
price quantity
0 20 6
1 40 9
2 60 12