Understand the idea
Express a calculation directly on a Series when possible. Vectorized arithmetic applies the operation to every value.
A small example
Prices [10, 20] × 1.1 become [11, 22]. Subtracting their original mean (15) gives [−5, 5].
Follow the code
Apply the idea to the supplied table. Read from top to bottom; the final line displays the result.
df["adjusted"] = (df["price"] * 1.1).round(2)
dfWhat each part does
df["price"] * 1.1- direct vectorised arithmetic
Other choices for later exercises
map(dictionary)- a value lookup
apply(lambda x: ...)- call a function on each value
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
- A price revision raises all unit prices in df by 10%.
- Add adjusted as the revised price rounded to two decimals, preserving the original price.
- Display df.
- Use vectorised arithmetic; do not use apply().
Hint
Keep raw and revised prices side by side.
Reveal solution
One way to do it. Keep any supplied setup in the editor and use this in the Your work section.
df["adjusted"] = (df["price"] * 1.1).round(2)
dfOptional stretch
Compare with df["{a}"].apply(lambda x: round(x * 1.1, 2)). Which expresses the intent more directly?