Need to apply an IF condition in Pandas DataFrame?

If so, in this tutorial, you’ll see 5 different ways to apply such a condition.

Specifically, you’ll see how to apply an IF condition for:

- Set of numbers
- Set of numbers and lambda
- Strings
- Strings and lambada
- OR condition

## Applying an IF condition in Pandas DataFrame

Let’s now review the following 5 cases:

### (1) IF condition – Set of numbers

Suppose that you created a DataFrame in Python that has 10 numbers (from 1 to 10). You then want to apply the following IF conditions:

- If the number is
*equal or lower*than 4, then assign the value of ‘True’ - Otherwise, if the number is
*greater*than 4, then assign the value of ‘False’

This is the general structure that you may use to create the IF condition:

df.loc[df['column name'] condition, 'new column name'] = 'value if condition is met'

For our example, the Python code would look like this:

import pandas as pd numbers = {'set_of_numbers': [1,2,3,4,5,6,7,8,9,10]} df = pd.DataFrame(numbers,columns=['set_of_numbers']) df.loc[df['set_of_numbers'] <= 4, 'equal_or_lower_than_4?'] = 'True' df.loc[df['set_of_numbers'] > 4, 'equal_or_lower_than_4?'] = 'False' print (df)

Here is the result that you’ll get in Python:

### (2) IF condition – set of numbers and *lambda*

You’ll now see how to get the same results as in case 1 by using *lambada, *where the conditions are:

- If the number is
*equal or lower*than 4, then assign the value of ‘True’ - Otherwise, if the number is
*greater*than 4, then assign the value of ‘False’

Here is the generic structure that you may apply in Python:

df['new column name'] = df['column name'].apply(lambda x: 'value if condition is met' if x condition else 'value if condition is not met')

And for our example:

import pandas as pd numbers = {'set_of_numbers': [1,2,3,4,5,6,7,8,9,10]} df = pd.DataFrame(numbers,columns=['set_of_numbers']) df['equal_or_lower_than_4?'] = df['set_of_numbers'].apply(lambda x: 'True' if x <= 4 else 'False') print (df)

This is the result that you’ll get, which matches with case 1:

### (3) IF condition – strings

Now, let’s create a DataFrame that contains only strings/text with 4 *names*: Jon, Bill, Maria and Emma.

The conditions are:

- If the name is
*equal to*‘Bill,’ then assign the value of ‘Match’ - Otherwise, if the name is
*not*‘Bill,’ then assign the value of ‘Mismatch’

import pandas as pd names = {'First_name': ['Jon','Bill','Maria','Emma']} df = pd.DataFrame(names,columns=['First_name']) df.loc[df['First_name'] == 'Bill', 'name_match'] = 'Match' df.loc[df['First_name'] != 'Bill', 'name_match'] = 'Mismatch' print (df)

Once you run the above Python code, you’ll see:

### (4) IF condition – strings and *lambada *

You’ll get the same results as in case 3 by using *lambada:*

import pandas as pd names = {'First_name': ['Jon','Bill','Maria','Emma']} df = pd.DataFrame(names,columns=['First_name']) df['name_match'] = df['First_name'].apply(lambda x: 'Match' if x == 'Bill' else 'Mismatch') print (df)

And here is the output from Python:

### (5) IF condition with OR

In the final case, let’s apply these conditions:

- If the name is ‘Bill’
**or**‘Emma,’ then assign the value of ‘Match’ - Otherwise, if the name is neither ‘Bill’ nor ‘Emma,’ then assign the value of ‘Mismatch’

import pandas as pd names = {'First_name': ['Jon','Bill','Maria','Emma']} df = pd.DataFrame(names,columns=['First_name']) df.loc[(df['First_name'] == 'Bill') | (df['First_name'] == 'Emma'), 'name_match'] = 'Match' df.loc[(df['First_name'] != 'Bill') & (df['First_name'] != 'Emma'), 'name_match'] = 'Mismatch' print (df)

Run the Python code, and you’ll get the following result:

## Applying an IF condition under an *existing* DataFrame column

So far you have seen how to apply an IF condition by creating a new column.

Alternatively, you may store the results under an *existing* DataFrame column.

For example, let’s say that you created a DataFrame that has 12 numbers, where the last two numbers are zeros:

**‘set_of_numbers’: [1,2,3,4,5,6,7,8,9,10,0,0]**

You may then apply the following IF conditions, and then store the results under the *existing* ‘set_of_numbers’ column:

- If the number is equal to 0, then change the value to 999
- If the number is equal to 5, then change the value to 555

import pandas as pd numbers = {'set_of_numbers': [1,2,3,4,5,6,7,8,9,10,0,0]} df = pd.DataFrame(numbers,columns=['set_of_numbers']) print (df) df.loc[df['set_of_numbers'] == 0, 'set_of_numbers'] = 999 df.loc[df['set_of_numbers'] == 5, 'set_of_numbers'] = 555 print (df)

Here are the before and after results, where the ‘5’ became ‘555’ and the 0’s became ‘999’ under the existing ‘set_of_numbers’ column:

On another instance, you may have a DataFrame that contains NaN values. You can then apply an IF condition to replace those values with zeros, as in the example below:

import pandas as pd import numpy as np numbers = {'set_of_numbers': [1,2,3,4,5,6,7,8,9,10,np.nan,np.nan]} df = pd.DataFrame(numbers,columns=['set_of_numbers']) print (df) df.loc[df['set_of_numbers'].isnull(), 'set_of_numbers'] = 0 print (df)

Before you’ll see the NaN values, and after you’ll see the zero values:

## Conclusion

You just saw how to apply an IF condition in Pandas DataFrame. There are indeed multiple ways to apply such a condition in Python. You can achieve the same results by using either *lambada, *or just sticking with Pandas.

At the end, it boils down to working with the method that is best suited to your needs.

Finally, you may want to check the following external source for additional information about Pandas DataFrame.