Manz
Manz

Reputation: 605

How to use multiple IF conditional statement using python

I am trying to use an Conditional IF statement using python but not getting the expected Output. Please suggest what can be done next to it.

Input Data :

Col1        Col2         Col3    Col4
No Gap     India         80
All Gaps   USA           85
No Gap     India         95
All Gaps   Maxico        90

The code i have been trying so far:

if df['Col1'] == "No Gaps" and df['Col2'] == "India" and df['Col3'] >=85:
    df['Col4'] = "No"
else:
    df['Col4'] = "Yes"

Getting the Error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Please Suggest.

Upvotes: 0

Views: 94

Answers (2)

Anurag Dabas
Anurag Dabas

Reputation: 24304

You can also do this by using apply() method:

df['col4']=df.apply(lambda x:'No' if (x['Col1'] == "No Gap") and (x['Col2'] == "India") and (x['Col3'] >=85) else 'yes',1)

Upvotes: 0

jezrael
jezrael

Reputation: 862431

Use numpy.where:

df['Col4'] = np.where((df['Col1'] == "No Gap") & 
                      (df['Col2'] == "India") & 
                      (df['Col3'] >=85), 'No', 'Yes')
print (df)
       Col1    Col2  Col3 Col4
0    No Gap   India    80  Yes
1  All Gaps     USA    85  Yes
2    No Gap   India    95   No
3  All Gaps  Maxico    90  Yes

Upvotes: 2

Related Questions