Python Forum

Full Version: if- elif- and condition issue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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!
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]
& operator?
Pandas DataFrame/Series classes implement the __rand__ method, i.e. behaviour of the & operator; This is elementwise ANDoperation in the code above.
Thanks All for suggestion.
I am now able to achieve the goal.