Python | Pandas Series.agg ()

Pandas Series.agg() is used to pass a function or list of functions to be applied to a series or even to each element of a series individually. In the case of a list of functions, multiple results are returned by the agg () method.

Syntax: Series.agg (func, axis = 0)

Parameters:
func: Function, list of function or string of function name to be called on Series.
axis: 0 or `index` for row wise operation and 1 or `columns` for column wise operation.

Return Type: The return type depends on return type of function passed as parameter.

Example # 1:
This example passes a lambda function that simply adds 2 to each value in the series. Since the function will be applied to each series value, the return type is also series. A random row of 10 elements is generated by passing an array using a random Numpy method.

# pandas module import

import pandas as pd

 
# numpy module import

import numpy as np

 
# create a random array of 10 elements

arr = np.random.randn ( 10 )

  
# create series from array

series = pd.Series (arr)

  
# calling the .agg () method

result = series.agg ( lambda num: num + 2

  
# display

print ( `Array before operation:` , series,

`Array after operation:` , result)

Output:

As shown in the output, f an function has been applied to each value, and 2 — to each value in the series.

Example # 2: Passing a list of functions

This example passes a list of some default Python functions and the agg method () returns multiple results in multiple variables.

# pandas module import

import pandas as pd

 
# numpy module import

import numpy as np

 
# create a random array of 10 elements

arr = np.random.randn ( 10 )

  
# create series from array

series = pd.Series (arr)

 
# create a list of function names

func_list = [ min , max , sorted ]

 
# calling the .agg () method
# passing the list functions

result1, result2, result3 = series.agg (func_list) 

 
# display

  print ( `Series before operation:` , series)

print (` Min = {} Max = {},

Sorted Series: {} `. format (result1, result2, result3))

Output:

As shown in the output, several results were returned. Min, Max and Sorted Array were returned in different variables result1, result2, result3 respectively.