Python lesson
If/else columns
Only Lagos in week 2 hit its target. Every other row says Below.
Try this lesson free →Example
np.where tests every row, and gives one label if the test is true and another if it's false:
df["Result"] = np.where(df["Sales"] >= df["Target"], "On target", "Below")
dfWeek Store Sales Target Result
0 W1 Lagos 260 300 Below
1 W1 Abuja 180 200 Below
2 W2 Lagos 330 300 On target
3 W2 Abuja 190 200 BelowKey points
import numpy as npnumpy comes with pandas. Load it once, as np.
np.where(test, …, …)The test, then the label if it's true, then the label if it's false.
df["Result"] = …Save the labels as a new column.
Put together: df["Result"] = np.where(df["Sales"] >= df["Target"], "On target", "Below").
Practice
1. Build a line that adds a Result column: On target if sales are at least the target, otherwise Below.
df["Result"] = np.where(df["Sales"] >= df["Target"], "On target", "Below")2. Build a line that adds a Band column: High if sales are over 250, otherwise Low.
df["Band"] = np.where(df["Sales"] > 250, "High", "Low")3. Add a column called Result: On target if Sales is at least Target, otherwise Below.
df["Result"] = np.where(df["Sales"] >= df["Target"], "On target", "Below")4. Add a column called Band: High if Sales is over 250, otherwise Low.
df["Band"] = np.where(df["Sales"] > 250, "High", "Low")5. Your manager wants to see which store-weeks missed target. Add a Result column (On target or Below), then show only the Below rows.
df["Result"] = np.where(df["Sales"] >= df["Target"], "On target", "Below")
df[df["Result"] == "Below"]Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →