Pandas DataFrame agg() method with examples

Spread the love

The agg() method in pandas allows you to apply a function or a list of function names to be executed along one of the axis of the DataFrame.

Syntax –

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

func – Function to use for aggregating the data.

axis – If 0 or ‘index’: apply function to each column. If 1 or ‘columns’: apply function to each row.

*args – Positional arguments to pass to func.

**kwargs – Keyword arguments to pass to func.

Examples –

1 . Create a DataFrame

Let’s create a dataframe to work with.

import pandas as pd

df = pd.DataFrame({'A':[1, 2, 3],
                  'B':[4, 5, 6],
                  'C':[7, 8, 9]})
df

2 . Apply a Function to the columns –

Now, Let’s say you want to calculate the sum of all the columns. For that you can use the agg() method in pandas.

df.agg(['sum'])

3 . Apply multiple Functions to columns –

You can also apply multiple functions together. Let’s say along with the sum you also want to calculate the mean of the columns.

df.agg(['sum','mean'])

4 . Apply different Functions to different columns –

You can also apply different functions to different columns using a dictionary.

df.agg({'A':['sum','mean'],
       'B':['mean','max']})

5 . Apply functions to Rows –

To apply a function to each rows of the dataframe you need to set the axis parameter to axis=1 or columns.

Let’s calculate the sum of each rows.

df.agg([sum], axis=1)

Rating: 1 out of 5.

Leave a Reply