Understand the idea
A conditional column chooses a value for each row based on a True/False test. Multiple rules are checked in their listed order.
A small example
For values [2, 4, 7], rules > 5 → high, > 3 → middle, otherwise low give [low, middle, high].
Follow the code
Apply the idea to the supplied table. Read from top to bottom; the final line displays the result.
import numpy as np
df["band"] = np.where(df["price"] > 2.1, "high", "low")
dfWhat each part does
import numpy as np- Load NumPy and name it np.
df["band"] =- Create a new band column from the result.
np.where(test, yes, no)- For each row, return yes when its test is True and no otherwise.
df["price"] > 2.1- The test: equality with 2.1 is False and goes to the otherwise branch.
"high", "low"- Use high for True and low for False.
Your inputs
The editable setup on the right creates df. Run executes the setup and your work from top to bottom.
| candy | flavour | price | rating | shelf |
|---|---|---|---|---|
| Gummy Bear | fruity | 1.2 | 4.1 | A |
| Choco Pop | chocolate | 2.1 | 4.6 | B |
| Mint Bite | mint | 1.5 | 3.8 | A |
| Berry Loop | fruity | 2.8 | 4.4 | B |
| Cocoa Cube | chocolate | 3.4 | 4.9 | A |
| Lemon Drop | fruity | 1.8 | 4 | B |
Your task · Follow
- Using df, add band: "high" when price exceeds 2.1, otherwise "low".
- Keep the changes in df and display it.
- Use: where().
Hint
The first np.where result belongs to True rows; equality does not satisfy a strict > test.
Reveal solution
One way to do it. Keep any supplied setup in the editor and use this in the Your work section.
import numpy as np
df["band"] = np.where(df["price"] > 2.1, "high", "low")
dfOptional stretch
Use np.select to add three bands. Choose non-overlapping rules and an explicit default.