Signup/Sign In

Pandas Series apply() Method

We can apply the numpy method or the python method to the entire Series and to the elements of Series respectively using the Python pandas Series.apply() method. This method applies the passed method to the values of the Series.

The below is the syntax of the Series.apply() method.

Syntax

Series.apply(func, convert_dtype=True, args=(), **kwds)

Parameters

func: It is the method that is the Python method or NumPy ufunc to apply.

convert_dtype: It represents the bool(True or False), and the default value is True.

args: It represents the tuple. It is the positional arguments passed to func after the series value.

**kwds: It is the additional keyword arguments passed to func.

Example: Pandas Series.apply() Method

Let's apply the np.pi method to the values of the Series. Here, in this example, we have passed the lambda method along with the numpy np.pi method, which multiplies the Series values with the pi value. See the below example.

#importing pandas as pd
import pandas as pd
#importing numpy as np
import numpy as np
#creating Series
s = pd.Series([1,2,3])
print(s.apply(lambda x: x*np.pi))


0 3.141593
1 6.283185
2 9.424778
dtype: float64

Example : Applying lower() function to the Series.apply() Method

Here, in this example, we apply the python lower() method to the Series. The Series.apply() method returns a Series by converting the elements of the Series to a lower case. See the below example.

#importing pandas as pd
import pandas as pd
#creating Series
s = pd.Series(['PYTHON','JAVA'])
print(s.apply(lambda x: x.lower()))


0 python
1 java
dtype: object

Example: Pandas Series.apply() Method

Here, in this example, we apply a lambda method along with the condition. If the condition satisfies, it returns True otherwise it returns False. See the below example.

#importing pandas as pd
import pandas as pd
#importing numpy as np
import numpy as np
#creating Series
s = pd.Series([2,1,8,4])
print(s.apply(lambda x: x >= 2 and x <=5))


0 True
1 False
2 False
3 True
dtype: bool

Conclusion

In this tutorial, we understand the Series.apply() method of the data frame. We learned the syntax and parameters of Series.apply() method and created different examples to better understand this topic.



About the author:
I like writing about Python, and frameworks like Pandas, Numpy, Scikit, etc. I am still learning Python. I like sharing what I learn with others through my content.