How to use IF-THEN-ELSE in Python the way you do it in SAS | by Valentin Nordstroem | Towards Data Science

I think I’ve used IF-THEN-ELSE Statement or conditional coding in almost every analysis or program I have developed in the last 30 years. It is very useful in both preparing and cleaning data.
IF-THEN-ELSE is an integrated part of the data step in SAS. We don’t have an object for a data step in Python, but can step through the data frame in a similar way and use IF-ELIF-ELSE as it is called in Python.
So in this article, We will look at what we do in SAS and see how we can do the same kind of conditional coding in Python. I’ll also show you alternative ways of running IF-ELIF-ELSE statements.
IF-END-ELSE It’s a straightforward concept. In pseudocode it looks something like this:
IF something is true, THEN return the first value,ELSE IF some other thing is true THEN return the second value,ELSE return the third value.
The most commonly used if-the-else coding on earth is putting people into different age groups.
First I will create a SAS data set with a random generated age around a mean of 50 and a variace of 100.
%%SAS%LET mu = 50; %let s2 = 100;DATA dd1.age;  DO id = 1000 TO 2000;    age = INT(&mu + sqrt(&s2) * rannor(1066));    OUTPUT;  END;  RUN;PROC PRINT DATA = dd1.age(OBS=5);RUN;
I want to use the same data in both SAS and Python so I can compare the results. Since you can not generate the same sequence of random numbers in both SAS and Python, I want to use the SAS data set in Python too.
For this article, I have used an environment where I can run both SAS and Python in the same Jupyter notebook.
You can find a description on how to do this guide at:
How to set up SAS and Python on Amazon Web Services Free Tier.
I import the SAS data set with pd.read_sas() in Python. Since SAS only have floating-point numbers, Python will import age as a float and not an integer, so I’ll convert age to an integer.
df = pd.read_sas('/age.sas7bdat')df.id = df.id.astype('int')df.age = df.age.astype('int')df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 1001 entries, 0 to 1000Data columns (total 2 columns):id     1001 non-null int64age    1001 non-null int64dtypes: int64(2)memory usage: 15.7 KB
We will create three groups: Young, Middle and Old age. Let’s define young age as people younger than 35 years. middle age for people between 35 and 60 and old age for people over 60 years old.
%%SASDATA age_group;	SET dd1.age;IF age <  35 THEN age_group = 'young age ';ELSE IF age >= 35 AND age <  60 THEN age_group = 'middle age';ELSE IF age >= 60 THEN age_group = 'old age   ';RUN; proc print DATA = age_group(obs=10);run;
We can do this with a simple IF-THEN statement for each condition, though, it is much better to use an ELSE IF after the first IF statement.
The reason is that this gives you more control over what is happening.
Notice the blank space I have added to the text in the age_group. That’s because I haven’t defined the length of the character variable. Therefore, I have to make sure it will capture all three values with the full text.
There are many different ways you can code conditional programming in Python. It is called IF-ELIF-ELSE. Python does not use the word THEN but uses a colon instead.
We will look at the following different ways:
Using a user-defined function
Using a lambda function
Using a for loop
Using a list comprehension
def age_grp_if(x):     if (x < 35) :        return 'young age'    elif (x < 60):        return 'middle age'    else:        return 'old age'age_group = df.copy()age_group['age_grp_if'] = age_group['age'].apply(age_grp_if)age_group.head()
First, you define the function with the argument you want in your condition and end it with a colon. The indented lines are telling Python to read them as part of the function definition.
You write the condition in brackets with a colon. In the next line, if the condition is true, you write the result you want to return and so forth... The last statement is an else: which will return if none of the above conditions are true.
To use the function in a DataFrame, you use the .apply(func) method on the column you want to use in the condition.
This method of defining your if-else coding in a function is very popular in Python and very easy to read. It’s different from what we are used to doing in SAS. But you can think about functions in SAS as a macro function.
You can use a lambda function instead of defining the function first and then applying it in your data step. The only problem with using lambda functions is that they are slightly difficult to read. This is because they do things in an opposing way.
The syntax for a lambda function using if-else is:
lambda args : return Value1 if condition1 else ( return value2 if condition2 else return value3)
The good thing about lambda functions is that you only need to write them on the fly when you need them.
age_group['age_grp_lambda'] = age_group['age'].apply(    lambda x : 'young age'  if (x < 35) else (               'middle age' if (x < 60) else 'old age'))age_group.head()
In case you have more than three conditions, the syntax will look like this:
lambda x : return Value1 if condition1 (    return value2 if condition2 (         return value3 if condition3 else return value4))age_group['age_grp_lambda4grp'] = age_group['age'].apply(    lambda x : 'young age'  if (x < 35) else (               'middle age' if (x < 60) else (               'senior age' if (x < 75) else 'old age')))age_group.head(10)
It is also possible to use a loop to construct an if-elif condition.
As we saw in the lecture regarding loops, you first build the loop in basic Python syntax and run it through the list of values in the age_group['age'] column.
age=[]for x in age_group['age']:    if (x < 35):        age.append('young age')    elif (x < 60):        age.append('middle age')    elif (x < 65):        age.append('senior age')    else :        age.append('old age')        age_group['age_grp_forloop'] = ageage_group.head()
You append the results to the list, age and then assign this list to a new column in the DataFrame.
Compare to the function method, the loop message is very easy to read, plus you type less.
The last method for coding if-elif statement is using list comprehension. A method that is sufficiently fast and even easier sometimes.
([return Value1 if condition1 else (  return value2 if condition2 else (  return value3 if condition3 else return value4)) for x in df['col']] )
The outer brackets of the list are only necessary when codes span over multiple lines.
age_group['age_grp_forxin'] = ([               'young age'  if (x < 35) else (               'middle age' if (x < 60) else (               'senior age' if (x < 65) else 'old age')) for x in age_group['age']                                ])age_group.head(10)
There are other ways you can do it in Python. Here I will show you how to use some functionalities from NumPy and Pandas to make conditional coding.
From Numpy you can use np.where and np.select.
From Pandas, you can use .loc[]
First, let’s look at how to use the np.where() function
np.where(contidion1, return Value1, return Value2)
Where you can substitute return Value2 with a new np.where()u001b for each condition
In the age group examples, the code will look like the following:
age_group['age_grp_whr'] = np.where(age_group['age'] < 35, 'young age',                           np.where(age_group['age'] < 60, 'middle age',                           np.where(age_group['age'] < 65, 'senior age',                                    'old age')))age_group.head(10)
Let’s look at how to use the np.select() function. This is very different from the other examples because you should first list all the conditions and then list all the return Values:
np.select([(condition1),(condition2),(condition3)],          [return Value1,return Value2,return Value3]
In the age group example, the code will look like this:
age_group['age_select'] = np.select([(age_group['age']<35),                                     (age_group['age']<60),                                     (age_group['age']>=60)],                                    ['young age',                                     'middle age',                                     'old age']) age_group.head(10)
The last way I’ll show you is to use the .loc method in Pandas. It’s quite handy as it’s got a straightforward syntax.
Remember, if you are not consistent in the coding of the conditions, you are more likely to make a mistake with your groupings. Also, if you’ve missed something, you won’t get any warnings.
With .loc you test if a condition is True, If it is True you assign a value and save the result in a new column.
The syntax is:
df.loc[condition, 'new var'] = return value
In our age group example, the code will look like this:
age_group.loc[age_group['age'] < 30, 'age_grp_loc'] = 'young age' age_group.loc[(age_group['age'] >= 30) & (age_group['age'] < 60), 'age_grp_loc'] = 'middle age' age_group.loc[age_group['age'] >= 60, 'age_grp_loc'] = 'old age' age_group.head(10)
In this article, we have seen how you can use conditional coding in Python in a similar way as you do in SAS. There are many different ways to do it in Python and you should choose the one you are most familiar with.
That been said, the different methods are not the same when it comes to speed and if you are working with a huge amount of data and have a lot of conditional coding, you should choose with care.
You can find out more about learning Python the way you work in SAS at my website: www.nordstroem.uk