## Pages

### How to modify data with IF-Else conditions in Python ### Python Tutorial 2.0

After writing second article of python "Data Exploration and Sub-setting", the topic for next article hovering in my mind was using If-else

I went with the flow of my mind and started writing about "how to apply if and else condition in python?"

Let's create a sample dataset for learning IF-Else based logical operations:

import pandas as p

Namelist = ['Tango','Tango','Tango','Jolly','Jolly','Jolly','John','John','John']

Subjectlist=['math','history','science','math','history','science','math','history','science']
Markslist=[51,62,86,60,68,85,56,94,52]

Exam_Dictionary={ 'Name' : Namelist ,

'Subject' : Subjectlist ,
'Marks' : Markslist }

Exam_Data=p.DataFrame(Exam_Dictionary, columns=['Name','Subject' ,'Marks'])

Exam_Data

Output :

### Let now learn the basic method of logical IF operation

Example -

if len(Exam_Data)==0 :
print('Dataset has zero observations')
else:
print('Dataset has observations')

Output :

Before going further about conditional statements, let me tell you about the map function.

map( ), it helps to easily apply operation on a collection.

Syntax : map( function, sequence)

Simple example:

def g(a) : return a*a                # we are defining a function

print(map(g, [1,2,3,4]))           # applying the function on the list

Output would be : [1,4,9,16]

In the below example, we are applying map function on variable of a dataframe.

Create a variable using if-else condition...

1. If-else

# Creating a function

Pass_Fail_Function=lambda x: 'Pass' if  x>=70 else 'Fail'

# The lambda function is a way to create temporary function in python. It is generally used with map() and reduce())

# Applying above mentioned function on marks field

Exam_Data['Result']=Exam_Data['Marks'].map(Pass_Fail_Function)

Output :

2. If-else if-else for more than two conditions

# Defining  function

if val<60 :
out='III'
elif val<80:
out='II'
else:
out='I'

return out

# Applying above mentioned function on marks field

Output :

Hope now you can easily use IF ELSE conditions in Python, a lot more is going to come, till then ...

Enjoy reading our other articles and stay tuned with us.

Kindly do provide your feedback in the 'Comments' Section and share as much as possible.