Python for Excel users · Lesson 6 of 14

IF, nested IF and IFS in pandas

Write Excel IF, nested IF, IFS, SWITCH and IF with AND/OR in pandas with np.where, np.select and .map, for a whole column at once.

About 16 minutes · code runs in your browser, nothing to install

=IF(B2>=1000, "Target met", "Below") is probably the most used Excel formula after SUM. pandas has no IF column function of its own; the usual tool is np.where from NumPy, the number library that pandas is built on.

IF: np.where

np.where(condition, value_if_true, value_if_false) has the same three parts as IF, in the same order, and works on the whole column.

Pythoneditable
import numpy as np
import pandas as pd

df = pd.DataFrame({
    "Rep": ["Ana", "Ben", "Chloe", "Dev", "Eva"],
    "Sales": [1450, 820, 2300, 990, 1210],
})
df["Status"] = np.where(df["Sales"] >= 1000, "Target met", "Below")
print(df)
Output
     Rep  Sales      Status
0    Ana   1450  Target met
1    Ben    820       Below
2  Chloe   2300  Target met
3    Dev    990       Below
4    Eva   1210  Target met

The results can be numbers or calculations too: =IF(B2>1000, B2*5%, 0) for a bonus becomes:

Pythoneditable
import numpy as np
import pandas as pd

df = pd.DataFrame({
    "Rep": ["Ana", "Ben", "Chloe", "Dev", "Eva"],
    "Sales": [1450, 820, 2300, 990, 1210],
})
df["Bonus"] = np.where(df["Sales"] > 1000, df["Sales"] * 0.05, 0)
print(df)
Output
     Rep  Sales  Bonus
0    Ana   1450   72.5
1    Ben    820    0.0
2  Chloe   2300  115.0
3    Dev    990    0.0
4    Eva   1210   60.5

IF with AND and OR

=IF(AND(B2>1000, C2="North"), …) uses the same & and | as filters in Filter and sort data like Excel AutoFilter, with each condition in brackets.

Pythoneditable
import numpy as np
import pandas as pd

df = pd.DataFrame({
    "Rep": ["Ana", "Ben", "Chloe", "Dev"],
    "Region": ["North", "South", "North", "South"],
    "Sales": [1450, 820, 900, 1210],
})
both = (df["Sales"] > 1000) & (df["Region"] == "North")
df["Prize"] = np.where(both, "Yes", "No")
print(df)
Output
     Rep Region  Sales Prize
0    Ana  North   1450   Yes
1    Ben  South    820    No
2  Chloe  North    900    No
3    Dev  South   1210    No

Nested IF and IFS: np.select

=IFS(B2>=2000, "Gold", B2>=1000, "Silver", TRUE, "Bronze") checks conditions in order and takes the first one that is true. np.select does exactly that: a list of conditions, a list of results, and a default for the final TRUE (or the last IF's false part).

Pythoneditable
import numpy as np
import pandas as pd

df = pd.DataFrame({
    "Rep": ["Ana", "Ben", "Chloe", "Dev", "Eva"],
    "Sales": [1450, 820, 2300, 990, 1210],
})
conditions = [df["Sales"] >= 2000, df["Sales"] >= 1000]
levels = ["Gold", "Silver"]
df["Level"] = np.select(conditions, levels, default="Bronze")
print(df)
Output
     Rep  Sales   Level
0    Ana   1450  Silver
1    Ben    820  Bronze
2  Chloe   2300    Gold
3    Dev    990  Bronze
4    Eva   1210  Silver

Order matters, as in IFS: put the strictest condition first, or every big seller would stop at Silver.

Tip: For number bands (0–999, 1000–1999, 2000+), pd.cut(df["Sales"], bins=[0, 1000, 2000, float("inf")], labels=["Bronze", "Silver", "Gold"], right=False) is another way to write the same nested IF.

SWITCH and CHOOSE: .map with a dictionary

=SWITCH(B2, "N", "North", "S", "South", "Other") replaces codes with names. In pandas, write the pairs in a Python dictionary ({"code": "name"}) and call .map(). Codes that are not in the dictionary become NaN (empty), so .fillna() supplies the "Other" value.

Pythoneditable
import pandas as pd

codes = pd.Series(["N", "S", "E", "N", "X"])
names = {"N": "North", "S": "South", "E": "East"}
print(codes.map(names).fillna("Other").tolist())
Output
['North', 'South', 'East', 'North', 'Other']

✎ Exercise

Give each student a grade: A for 90 or more, B for 75 or more, C for 50 or more, otherwise F. Also add a column Pass that is Yes for 50 or more and No otherwise. Print the table.

Hint: np.select with three conditions from highest to lowest and default="F"; np.where for Pass.

Your codewrite your answer, then Run
import numpy as np
import pandas as pd

df = pd.DataFrame({
    "Name": ["Ana", "Ben", "Chloe", "Dev", "Eva"],
    "Score": [93, 48, 75, 61, 89],
})
# your code here

Expected output:

    Name  Score Grade Pass
0    Ana     93     A  Yes
1    Ben     48     F   No
2  Chloe     75     B  Yes
3    Dev     61     C  Yes
4    Eva     89     B  Yes
Show a solution
Solutioneditable
import numpy as np
import pandas as pd

df = pd.DataFrame({
    "Name": ["Ana", "Ben", "Chloe", "Dev", "Eva"],
    "Score": [93, 48, 75, 61, 89],
})
conditions = [df["Score"] >= 90, df["Score"] >= 75, df["Score"] >= 50]
df["Grade"] = np.select(conditions, ["A", "B", "C"], default="F")
df["Pass"] = np.where(df["Score"] >= 50, "Yes", "No")
print(df)
Output
    Name  Score Grade Pass
0    Ana     93     A  Yes
1    Ben     48     F   No
2  Chloe     75     B  Yes
3    Dev     61     C  Yes
4    Eva     89     B  Yes

Check yourself

1. What is the pandas way to write =IF(B2>10, "High", "Low") for a whole column?

2. In np.select, what plays the role of IFS's final TRUE, "Other"?

3. A code missing from the dictionary given to .map() becomes…

Spotted a mistake on this page? Tell us