fitness_center
Exercise 4.3
Decline Rate Calculator
Level 2
Chapter 4: NumPy & PandasdescriptionProblem
Given a pandas DataFrame with a monthly oil rate, compute the month-over-month decline rate as a new column called "decline_pct":
Two requirements:
- The first row has no previous month, so its
decline_pctmust beNaN. - Use
df.shift()rather than a Pythonforloop. The whole column
should fall out of one vectorised expression.
Data:
month: 1 2 3 4 5 6
rate: 1000 920 860 800 760 720lightbulbHints (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.