Python Forum
if- elif- and condition issue
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
if- elif- and condition issue
#1
Hi All,

Need your help on one issue.
I have a dataframe 'df' which has 3 columns of 'object' data type- opt1,opt2,opt3
Now I need to create a new column 'var' which will have followings-
1. if opt2 and opt 3 are None/Null/Empty and opt1 is not None/Null/Empty:
then df[var] = df[opt1]
2. elif opt1 and opt 3 are None/Null/Empty and opt2 is None/Null/Empty:
then df[var] = df[opt1] + '|' + df[opt3]
3. elif opt1 and opt 2 are None/Null/Empty and opt3 is None/Null/Empty:
then df[var] = df[opt1] + '|' + df[opt2]
4. else: df[var] = df[opt1] + '|' + df[opt2] + '|' + df[opt3]

Please suggest me to put above conditions in Python 3.6 or share me any better approach.

Thanks!
Reply
#2
Firstly, you need to rewrite each condition separately, e.g.:

cond1 = df.opt2.isnull()&df.opt3.isnull()&~df.opt1.isnull()
cond2 = df.opt1.isnull()&df.opt3.isnull()&~df.opt2.isnull()
cond3 = df.opt1.isnull()&df.opt2.isnull()&~df.opt3.isnull()
cond4 = ~(cond1|cond2|cond3)

# cond1
df['var'][cond1] = df['opt1'][cond1]

# cond2
df['var'][cond2] = df['opt1'][cond2] + '|' + df['opt3'][cond2]

# cond3
df['var'][cond3] = df['opt1'][cond3] + '|' + df['opt2'][cond3]

df['var'][cond4] = df['opt1'][cond4] + '|' + df['opt2'][cond4] + '|' + df['opt3'][cond4]
Reply
#3
& operator?
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
Pandas DataFrame/Series classes implement the __rand__ method, i.e. behaviour of the & operator; This is elementwise ANDoperation in the code above.
Reply
#5
Thanks All for suggestion.
I am now able to achieve the goal.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020