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. By Pranit Sharma Last updated : September 23, 2023

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.

Problem statement

Given a Pandas DataFrame, we have to create a new column based on if-elif-else condition.

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

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.

Note

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 program 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

The output of the above program is:

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 »

Comments and Discussions!

Load comments ↻





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