Python Forum
if- elif- and condition issue - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: if- elif- and condition issue (/thread-10147.html)



if- elif- and condition issue - PrateekG - May-15-2018

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!


RE: if- elif- and condition issue - scidam - May-16-2018

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]



RE: if- elif- and condition issue - wavic - May-16-2018

& operator?


RE: if- elif- and condition issue - scidam - May-16-2018

Pandas DataFrame/Series classes implement the __rand__ method, i.e. behaviour of the & operator; This is elementwise ANDoperation in the code above.


RE: if- elif- and condition issue - PrateekG - May-16-2018

Thanks All for suggestion.
I am now able to achieve the goal.