Creating a new column based on if-elif-else condition

Given a Pandas DataFrame, we have to create a new column based on if-elif-else condition.
Submitted by Pranit Sharma, on June 26, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mainly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and the data.

If-elif-else condition is used whenever we check some condition, if the condition is satisfied, it performs whatever has defined inside it.

To create a new column based on if and else conditions, we will first define a function to apply certain if and else conditions and finally we will create a new column with the values returned by the function.

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,

Python code to create a new column based on if-elif-else condition

# Importing pandas package
import pandas as pd

# Defining a function
def function(row):
        if row['One'] == row['Two']:
                val = 0
        elif row['One'] > row['Two']:
                val = 1
        else:
                val = -1
        return val

# Creating a dictionary
d = {
    'One':[1,2,3,4],
    'Two':[0.1,0.2,1,2]
}

# Creating dataframe
df = pd.DataFrame(d)

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

# Calling the function with apply
df['New'] = df.apply(function,axis=1)

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

Output:

Created DataFrame:
    One  Two
0    1  0.1
1    2  0.2
2    3  1.0
3    4  2.0 

Modified DataFrame:
    One  Two  New
0    1  0.1    1
1    2  0.2    1
2    3  1.0    1
3    4  2.0    1

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


What's New (MCQs)



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.