w3resource

Applying a Custom Function to a Pandas Series with map()


Pandas: Custom Function Exercise-4 with Solution


Write a Pandas program that uses map() function to apply a function to a Series.

This exercise demonstrates how to use map() to apply a custom function to a Pandas Series.

Sample Solution:

Code :

import pandas as pd

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

# Define a custom function to double the value
def double(x):
    return x * 2

# Apply the custom function to each element in the Series using map()
s_doubled = s.map(double)

# Output the result
print(s_doubled)

Output:

0     2
1     4
2     6
3     8
4    10
dtype: int64                                

Explanation:

  • Created a Pandas Series with 5 values.
  • Defined a function double() that doubles its input.
  • Applied the double() function to the Series using map().
  • Returned a new Series where each value has been doubled.

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.