# How can we apply an anonymous function to the pandas series?

The pandas series constructor has an apply() which accepts any user-defined function that applies to the values of the given series object.

In the same way, we can apply an anonymous function over a pandas series object. We can use this apply() method on both the pandas data structures DataFrame and Series. It Performs element-wise transformations and returns a new series object as a result.

## Example 1

# import pandas package
import pandas as pd
import numpy as np

# create a pandas series
s = pd.Series(np.random.randint(10,20,5))
print(s)

# Applying an anonymous function
result = s.apply(lambda x: x**2)
print('Output of apply method',result)

## Explanation

In the following example, we are using a lambda function as an anonymous function to the apply() method.

Initially, we have created a pandas.Series object “s” with 5 integer values by using the NumPy random module, and then we applied the square function using the apply() method with a lambda function.

## Output

0 12
1 17
2 11
3 15
4 15
dtype: int32

Output of apply method
0 144
1 289
2 121
3 225
4 225
dtype: int64

The code s.apply(lambda x:x**2) will calculate the square of each value of the series elements. Here the lambda is an anonymous function. The apply() method will return a new series object that is displayed in the above output block.

## Example 2

# import pandas package
import pandas as pd
import numpy as np

# create a pandas series
s = pd.Series(np.random.randint(10,20,5))
print(s)

# Applying an anonymous function
result = s.apply(lambda x : True if x%2==0 else False)
print('Output of apply method',result)

## Explanation

Let’s take another pandas series object and apply an anonymous function, here we have applied a lambda function for identifying the even and odd values of the series object “s”.

## Output

0 15
1 18
2 15
3 14
4 18
dtype: int32

Output of apply method
0 False
1 True
2 False
3 True
4 True
dtype: bool

The output of the apply() method of the given example is displayed in the above block along with the actual series object “s”.

The resultant series object is having boolean values (True and Fales), True is representing the even numbers and False is for odd numbers.