S.Nicko S.Nicko - 3 months ago 27
SQL Question

Double IIF Statement in Python

I have an SQL code that has a double IIF statement in it, that is, the if true part is another IIF statement and I m trying to recreate this in python using

np.where


the SQL code is:

IIF ([STATE] Is Null, IIF ([COUNTRY] Is Null,'No Country',[COUNTRY]), [STATE])


I've tried this:

DF['NewCol'] = np.where(DF['STATE'].isnull(),(np.where(DF['COUNTRY'].isnull(),'No Country','DF['COUNTRY']'),DF['STATE']))


any help appreciated

Answer

I think you need:

DF['NewCol'] = np.where(DF['STATE'].isnull(),
               np.where(DF['COUNTRY'].isnull(),'No Country', DF['COUNTRY']),DF['STATE'])

Sample:

DF = pd.DataFrame({'STATE':[np.nan,'a','b',np.nan],
                   'COUNTRY':[np.nan,'c',np.nan, 'd']})

print (DF)
  COUNTRY STATE
0     NaN   NaN
1       c     a
2     NaN     b
3       d   NaN

DF['NewCol'] = np.where(DF['STATE'].isnull(),
               np.where(DF['COUNTRY'].isnull(),'No Country', DF['COUNTRY']),DF['STATE'])

print (DF)
  COUNTRY STATE      NewCol
0     NaN   NaN  No Country
1       c     a           a
2     NaN     b           b
3       d   NaN           d

If need first in output column values of COUNTRY column:

DF['NewCol'] = np.where(DF['COUNTRY'].isnull(),
               np.where(DF['STATE'].isnull(),'No Country', DF['STATE']),DF['COUNTRY'])

print (DF)
  COUNTRY STATE      NewCol
0     NaN   NaN  No Country
1       c     a           c
2     NaN     b           b
3       d   NaN           d