Series.agg()
functionThe pandas Series.agg()
function applies a function or list of functions to the elements in a series along a given axis and returns the result.
Series.agg(func, axis=0)
func
: It represents the function or list of functions used to perform operations on the series elements.axis
: It indicates the axis in which the operation is to be performed. The value 0
and 1
indicate rows and columns, respectively. The default is 0
.Note: If a list of functions is used, the
Series.agg()
function returns multiple results.
The following code will demonstrate how to use the Series.agg()
function in pandas.
import pandas as pd # create Series my_series = pd.Series([17, 4, 28, 15, 23, 7, 9]) # multiple each element in the by the power of 2 # using agg() and passing the lambda function print(my_series.agg(lambda x: x **2))
In the code above:
Line 1: We import the pandas library.
Lines 4: We create the Series, my_series
.
Line 8: We use the agg()
function, then we pass a lambda
function to multiple each element in the Series
by the power of 2.
import pandas as pd # create Series my_series = pd.Series([17, 4, 28, 15, 23, 7, 9]) # sum the element in the series # using agg() and passing the sum method print(my_series.agg([min, sum, len, max]))
In the code above:
Line 1: We import the pandas
library.
Lines 4: We create a series my_series
.
Line 8: We use the agg()
function, then we pass a list of functions:
min
function finds the minimum element in the Series
.sum
function finds the minimum element in the Series
.len
function finds the len of the Series
.max
function finds the maximum element in the Series
.Note: Each function is enclosed in a square bracket and separated by a comma. Also, you can add as many functions as needed.
RELATED TAGS
CONTRIBUTOR
View all Courses