Exerciseschevron_rightChapter 4chevron_right4.3
fitness_center

Exercise 4.3

Decline Rate Calculator

Level 2
Chapter 4: NumPy & Pandas
descriptionProblem

Given a pandas DataFrame with a monthly oil rate, compute the month-over-month decline rate as a new column called "decline_pct":

decline_pcti=ratei1rateiratei1×100\text{decline\_pct}_i = \frac{\text{rate}_{i-1} - \text{rate}_i}{\text{rate}_{i-1}} \times 100

Two requirements:

  1. The first row has no previous month, so its decline_pct must be NaN.
  2. Use df.shift() rather than a Python for loop. The whole column

should fall out of one vectorised expression.

Data:

month:  1     2    3    4    5    6
rate:   1000  920  860  800  760  720
lightbulbHints (0/3)

Stuck? Reveal hints one at a time — they progress from nudge to near-solution.

codeYour solution
main.py
visibilityReveal reference solutionexpand_more

Try solving it yourself first — the hints walk you through it. The solution below is one valid approach; yours may differ and still be correct.

import pandas as pd

df = pd.DataFrame({
    "month": [1, 2, 3, 4, 5, 6],
    "rate":  [1000, 920, 860, 800, 760, 720],
})

prev = df["rate"].shift(1)
df["decline_pct"] = (prev - df["rate"]) / prev * 100

print(df)

lockCopying code is a Full Access feature.