Pandas Series Agg Method

PythonPythonBeginner
Practice Now

Introduction

In this lab, we will learn about the agg() method in the Pandas Series object. The agg() method allows us to apply one or more aggregation functions to the elements of a Series along a specified axis. It returns a scalar value when called with a single function and multiple values when called with multiple functions.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Import the necessary libraries

First, we need to import the pandas library, which is used for data manipulation and analysis.

import pandas as pd

Create a Series

Next, we will create a Series object with some sample data.

s = pd.Series([2, 3, 4])

Aggregate with a single function

Now, let's aggregate the elements of the Series using a single function. We will use the sum(), min(), max(), mean(), and count() functions as examples.

print("The sum of the series elements is:", s.agg('sum'))
print("The min of the series elements is:", s.agg('min'))
print("The max of the series elements is:", s.agg('max'))
print("The mean of the series elements is:", s.agg('mean'))
print("The count of the series elements is:", s.agg('count'))

Aggregate with multiple functions

We can also aggregate the elements of the Series using multiple functions. Here, we pass a list of functions to the agg() method.

print("The output of the agg method is:\n", s.agg(['sum', 'min', 'max']))

Aggregate with a user-defined function

Finally, we can aggregate the elements using a user-defined function. In this example, we will create a function called add() that adds 1 to elements greater than 3 and returns the same element otherwise.

def add(x):
    if x > 3:
        return x + 1
    else:
        return x

print("After aggregating the result is:\n", s.agg(add))

Summary

In this lab, we learned how to use the agg() method in the Pandas Series object. We saw how to aggregate elements using built-in functions, multiple functions, and user-defined functions. The agg() method is a powerful tool for summarizing and analyzing data in a Series.

Other Python Tutorials you may like