What does the apply() method do in the pandas series?

PandasServer Side ProgrammingProgramming

The apply() method in pandas Series is used to call our function on a series object. By using this apply() method we can apply our own function on our series object.

The apply() method is very similar to some other pandas series methods like agg() and map(). Here the difference is we can apply a function on values of the given series object.

Example 1

# import pandas package
import pandas as pd

# create a pandas series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)

# Applying a function
result = s.apply(type)
print('Output of apply method',result)

Explanation

In the following example, we have created a pandas.Series object “s” with 10 integer values, and by using the apply() method we execute the type function of all elements of the series object “s”.

The apply() method operations are similar to the agg() method but the difference is agg() method is only for aggregation operations whereas apply() method can be used to apply any method over the series data.

Output

0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
9 10
dtype: int64

Output of apply method
0  <class 'int'>
1  <class 'int'>
2  <class 'int'>
3  <class 'int'>
4  <class 'int'>
5  <class 'int'>
6  <class 'int'>
7  <class 'int'>
8  <class 'int'>
9  <class 'int'>
dtype: object

The pandas series apply() method will return a new series object, with the data type representation of each value of the given series object “s”.

Example 2

# import pandas package
import pandas as pd

# create a pandas series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)

# Apply power(2) function
result = s.apply(pow, args=(2,))
print('Output of apply method',result)

Explanation

Let’s take another example and apply a function with arguments to the series object by using the apply() method. Here we have applied the pow function with argument value 2.

Output

0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
9 10
dtype: int64
Output of apply method
0   1
1   4
2   9
3  16
4  25
5  36
6  49
7  64
8  81
9 100
dtype: int64

The output of the apply() method is displayed in the above block along with the actual series object “s”. And the pow() function is applied to the series elements and the resultant output is returned as another series object.

To send the arguments of the function in the apply() method we need to use the args keyword arguments.

raja
Updated on 09-Mar-2022 06:13:44

Advertisements