w3resource

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

Pandas: Custom Function Exercise-15 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/pandas-apply-a-lambda-function-to-a-series-using-map.php