Module 4 · Lesson 5
Putting It Together: Analyzing Daily Temperatures
Let’s generate a month of synthetic daily high temperatures (°C) and use
everything from this module — aggregation, argmin/argmax, sorting, and
counting — to analyze it in one exercise.
rng = np.random.default_rng(seed=7)
days = np.arange(1, 31)
# a gentle seasonal wave plus daily noise, just to have realistic-looking data
temps = 18 + 4 * np.sin(np.linspace(0, np.pi, 30)) + rng.normal(0, 1.5, size=30)
temps = np.round(temps, 1)
plt.figure(figsize=(8, 3))
plt.plot(days, temps, marker="o")
plt.xlabel("Day of month")
plt.ylabel("High temp (°C)")
plt.title("Synthetic daily high temperatures")
plt.show()
print(temps)
Output:
[18. 18.9 18.4 17.9 19. 18.6 20.5 22.8 20.3 20.4 22.3 22.3 22. 20.6
22. 23. 19.9 21.2 18.9 19.6 18.5 20.7 18.8 20.8 20.3 19.4 15.5 18.1
18.4 18.2]
Temperature report
Write temperature_report(temps, threshold) that takes the 1-D array of
daily temperatures and a threshold value, and returns a dict with:
"hottest_day": the 1-based day number (int) with the highest temp (day 1 =temps[0])"coldest_day": the 1-based day number (int) with the lowest temp"mean": the mean temperature (float)"std": the standard deviation (float)"days_above_threshold": how many days exceededthreshold(int)"sorted_desc": the temperatures sorted from hottest to coldest (array)
Use argmax/argmin, mean/std, boolean indexing + .sum() (or
np.count_nonzero), and np.sort — don't write a loop.
💡 Hint
temps.argmax() is a 0-based flat index — add 1 to get the day number. (temps > threshold).sum() counts how many exceed the threshold. np.sort(temps)[::-1] sorts hottest-first.
✅ Solution
def temperature_report(temps, threshold):
return {
"hottest_day": int(temps.argmax()) + 1,
"coldest_day": int(temps.argmin()) + 1,
"mean": float(temps.mean()),
"std": float(temps.std()),
"days_above_threshold": int((temps > threshold).sum()),
"sorted_desc": np.sort(temps)[::-1],
}
🎯 Key Takeaways
axis=0reduces down columns (one result per column);axis=1reduces across rows (one result per row).argmin/argmaxlocate where an extreme value is;np.unravel_indexturns a flat index back into(row, col)coordinates.np.sortreturns a copy,arr.sort()sorts in place, andnp.argsortgives you an ordering you can apply to another array.np.unique(..., return_counts=True)is your go-to for frequency analysis without writing a loop.- Real analysis is usually a short chain of these tools, not a single call.
Next up: Module 5 — Linear Algebra & Random, where you’ll work with vectors, matrices, and NumPy’s modern random number generator.