Python - Pandas apply function with two arguments to columns

Given a Pandas dataframe, we need to use apply method to pass a function which accepts two arguments.
By Pranit Sharma Last updated : December 21, 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.

apply() function with two arguments to columns in Pandas

To use apply() method to pass a function that accepts two arguments, we will simply use apply() method inside which we can use either the lambda function to operate the function on each value or we can directly apply the function on any particular column value.

Whenever we want to perform some operation on the entire DataFrame, we use apply() method. The apply() method passes the columns of each group in the form of a DataFrame inside the function which is described in apply() method.

The function 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 how to use apply method to pass a function which accepts two arguments

# Importing pandas package
import pandas as pd

# Creating a Dictionary
d = {
    'PCM':[250,280,233],
    'HE':[173,110,168]
}

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

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

# Defining a function
def calculate_percentage(pcm,he):
    if (pcm+he)/5>=60:
        return "First"
    elif (pcm+he)/5>=50 and (pcm+he)/5<60:
        return "Second"
    elif (pcm+he)/5>=40 and (pcm+he)/5<50:
        return 'Third'
    elif (pcm+he)/5>=30 and (pcm+he)/5<40:
        return "Fourth"
    else:
        return "Fail"

# Using apply method
df['Division'] = df.apply(lambda x: calculate_percentage(x['PCM'], x['HE']),axis=1)

# Display modified DataFrame
print("Modified DataFrame\n",df)

Output:

Example: Apply function with two arguments to columns

In this example, we have used the following Python topics that you should learn:

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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