Pandas Series.agg()


Pandas Series.agg() Function Tutorial

In this tutorial, we'll go through examples for Series.agg() method, which is used to apply one or more aggregation functions to the elements of a Pandas Series.

The syntax of Series.agg(func, axis=0, *args, **kwargs) is:

Series.agg(func, axis=0, *args, **kwargs)

where

ParameterDescription
func[Optional]
The aggregation function or a list of aggregation functions to apply.
axis[Optional]
The axis along which the aggregation is applied.
Default is 0 (along rows).
*args, **kwargsAdditional arguments and keyword arguments to pass to the aggregation functions.

The Series.agg() method returns a scalar value when only a single function is given as argument for the func parameter, or a Series object when a list is given for the func parameter.


Examples

1. Calculate sum of the elements in Series using Series.agg() method

In this example, we shall find the sum of the elements in the given Series object series using Series.agg() method.

Python Program

import pandas as pd

# Take a series
series = pd.Series([10, 15, 20, 25, 30])

# Calculate the sum using agg()
result = series.agg('sum')

# Print original series and result
print("Original Series:")
print(series)
print("\nAggregated sum:")
print(result)

Output

Original Series:
0    10
1    15
2    20
3    25
4    30
dtype: int64

Aggregated sum:
100

2. Calculate sum() and mean() using Series.agg() method

In this example, we shall find the sum and mean of the elements in the given Series object series using Series.agg() method.

Python Program

import pandas as pd

# Take a series
series = pd.Series([10, 15, 20, 25, 30])

# Calculate the sum and mean using agg
result = series.agg(['sum', 'mean'])

# Print original series and result
print("Original Series:")
print(series)
print("\nAggregated result:")
print(result)

Output

Original Series:
0    10
1    15
2    20
3    25
4    30
dtype: int64

Aggregated result:
sum     100
mean     20
dtype: int64

Summary

In this Pandas Tutorial, we have learnt about Series.agg() method, and gone through examples to apply one or more aggregation functions to the elements of a Pandas Series, providing summary statistics and insights into the data.


Python Libraries