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

Given a pandas dataframe, we have use pandas groupby() and apply() methods with arguments.
Submitted by Pranit Sharma, on September 20, 2022

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.

Pandas - groupby() and apply() methods with arguments

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.

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 code 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 »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.