How to map a function using multiple columns in pandas?

Learn, how to map a function using multiple columns in Python Pandas?
Submitted by Pranit Sharma, on December 02, 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.

Problem statement

Suppose we are given a dataframe with multiple columns and we need to pass some of these columns into a function that takes scalar values and returns a scalar value. In short, we need to apply this map function and create a new column in the dataframe with the result returned by this function.

Mapping a function using multiple columns in pandas

For this purpose, we will simply use the apply method inside which we will write a comprehension statement by using some of the columns of the dataframe.

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

Let us understand with the help of an example,

Python program to map a function using multiple columns in pandas

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'a':[1,2,3,4,5],
    'b':[6,7,8,9,10],
    'c':[11,12,13,14,15]
}

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

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

# Defining a function
def fun(a,b):
    return a*b

# Calling this function which takes 
# values from multiple columns
df['d'] = df.apply(lambda x: fun(a = x['a'], b = x['b']), axis=1)

# Display result
print("Result:\n",df)

Output

The output of the above program is:

Example: How to map a function using multiple columns in pandas?

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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