How to apply a function with multiple arguments to create a new Pandas column?

Given a Pandas DataFrame, we have to apply a function with multiple arguments.
Submitted by Pranit Sharma, on June 02, 2022

Pandas is a special tool which 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 structure in pandas. DataFrames consists of rows, columns and the data.

We can insert a new column in a DataFrame whose values are defined from a function which takes multiple arguments. A simple comprehension function or lambda function can be used to continuously call the function with multiple arguments.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {

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

# Display the original DataFrame
print("Original DataFrame:\n",df,"\n")


Example 1: Apply a function with multiple arguments

Now, defining and calling the function,

# Defining a function
def fun(x,y):
    return x+y

# Adding a new column into the DataFrame
df['New_col'] = df.apply(lambda x: fun(x['A'], x['B']), axis=1)

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


Example 2: Apply a function with multiple arguments

Python Pandas Programs »


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

© some rights reserved.