Use pandas groupby() and apply() methods with arguments

Given a pandas dataframe, we have use pandas groupby() and apply() methods with arguments. By Pranit Sharma Last updated : September 30, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Use of groupby() and apply() methods with arguments

Let's learn about these methods.

The groupby() Method

The groupby() is a simple but very useful concept in pandas. By using it, we can create grouping of certain values and perform some operations on those values.

The groupby() method splits the object, applies some operations, and then combines them to create a group hence large amount of data and computations can be performed on these groups.

Basically, the groupby operation packs the data into an object and if we want to check out that data, we need to access that object and we are going to get all the keys to this object.

The apply() Method

On the other hand, apply() method clearly passes the columns of each group in the form of a DataFrame inside the function which is described in apply() method.

The method which is described inside the apply() method returns a series or DataFrame (NumPy array or even a list).

Let us understand with the help of an example,

Python program to demonstrate the use of pandas groupby() and apply() methods with arguments

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'a':[1,1,3,4,3],
    'b':[7,7,0,2,4],
    'c':[1,6,6,3,1]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original DataFrames
print("Created DataFrame:\n",df,"\n")

# Defining a function to use apply method
def fun(ser, n):
     return ser.max()+n

res = df.apply(fun,args=(10,))

# Display res
print("Result of apply:\n",res,"\n")

# Using groupby
res = df.groupby('a').apply(fun, n=10)

# Display res
print("Result after groupby:\n",res)

Output

Example: pandas groupby() and apply() methods with arguments

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.