Creating a new column in Pandas by using lambda function on two existing columns

Learn, how to create a new column in Pandas by using lambda function on two existing columns in Python? By Pranit Sharma Last updated : October 06, 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.

Problem statement

Suppose we are given the Pandas dataframe with some columns 'A' and 'B' and we need to create a column 'C' whose values will depend on the values of 'A' and 'B'.

Let us say we need to filter that particular value from columns A and B which has the longest length.

Creating a new column in Pandas by using lambda function on two existing columns

For this purpose, we will use the Lambda function in such a way that we will find the maximum length value from columns A and B for each row by using the max function inside the Lambda expression and store the intermediate results as the value of column C.

Let us understand with the help of an example,

Python program to create a new column in Pandas by using lambda function on two existing columns

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a DataFrame
df = pd.DataFrame({
    'A':['Mahabharat','Shakuni'],
    'B':['Ramcharitmanas','Ravan']
})

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

# Using lambda function with a condition
df['C'] = df.apply(lambda x: max(len(x['A']), len(x['B'])), axis=1)

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

Output

The output of the above program is:

Example: Creating a new column in Pandas by using lambda function on two existing columns

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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