If else equivalent where function in pandas python – create new variable

In this Tutorial we will see how to create a new variable using where function which is an equivalent of if else function.  Let’s see how to

  • Create new variable in pandas python using where function.

First let’s create a dataframe

import pandas as pd
import numpy as np

df1 = {
    'State':['Arizona AZ','Georgia GG','Newyork NY','Indiana IN','Florida FL'],
   'Score':[4,47,55,74,31]}

df1 = pd.DataFrame(df1,columns=['State','Score'])
print(df1)

dataframe df1 will be

ifelse operator in pandas python where 1

 

Create new column in pandas python with where function:


df1['Grade'] = np.where(df1['Score'] >=40, 'Pass','Fail')
df1

ifelse operator in pandas python where 2

 

Again create one more class as “Distinction” as shown below


df1['Grade'] = np.where(df1['Score'] >=70, 'Distinction',df1['Grade'])
df1

so the result will be

ifelse operator in pandas python where 3

 

If else equivalent where function in pandas python – create new variable p                                                                                                           If else equivalent where function in pandas python – create new variable n