w3resource

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


4. Apply a Function to a Series Using map()

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to use the map() function to convert a Series of categorical labels into numeric codes.
  • Write a Pandas program to apply map() to replace specific values in a Series based on a provided dictionary.
  • Write a Pandas program to use map() on a Series to strip whitespace and convert all text to lowercase.
  • Write a Pandas program to transform a Series by mapping each value to its square using a lambda function with map().

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.