w3resource

Applying a Lambda Function to a Series using map() in Pandas


15. Use map() with Lambda for Custom Function

Write a Pandas program that uses map() function to apply a custom function with a Lambda.

In this exercise, we have used map() function with a lambda expression to apply a simple mathematical operation on a Series.

Sample Solution :

Code :

import pandas as pd

# Create a sample Series
s = pd.Series([1, 2, 3, 4, 5])

# Apply a lambda function to multiply each element by 3 using map()
s_multiplied = s.map(lambda x: x * 3)

# Output the result
print(s_multiplied)

Output:

0     3
1     6
2     9
3    12
4    15
dtype: int64                                   

Explanation:

  • Created a Pandas Series with five elements.
  • Used a lambda function to multiply each element by 3.
  • Applied the lambda function to the Series using map().
  • Outputted the resulting Series, where all values have been multiplied by 3.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to use the map() function with a lambda to convert numerical codes in a Series to descriptive labels.
  • Write a Pandas program to apply a lambda function via map() that adds a prefix to each string in a Series.
  • Write a Pandas program to use map() with a lambda to transform a Series of dates from string to datetime format.
  • Write a Pandas program to use map() to apply a lambda function that computes the square of each number in a numeric Series.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.