TExcelTAD
Home › NumPy › NumPy Mini Project

NumPy Mini Project

In this project you'll analyse a year of weather data from a (simulated) weather station, step by step. It brings together much of the course: random generators, array creation, NaN handling, aggregations, boolean masks, np.diff, broadcasting, sorting and plotting.

By the end, the program produces a monthly report like this, finds heat waves and unusual days, and draws a chart of the whole year:

text
month  mean   min   max
Jan     0.8  -5.4   6.1
...

A real station would hand you a CSV file; since the playgrounds can't read files, we simulate the measurements with a seeded generator. Every step is a complete program you can run and modify, and each starts by rebuilding the same data, so you can jump to any step.

Step 1: Simulate a year of temperatures

Daily mean temperatures follow the seasons (cold in January, warm in July) plus day-to-day noise. We model the season with a cosine curve and add normal noise:

python · try it yourself
import numpy as np

rng = np.random.default_rng(7)
days = np.arange(365)                                   # day 0 = 1 January
season = 12 - 10 * np.cos(2 * np.pi * (days - 15) / 365)   # 2 C in winter, 22 C in summer
temps = (season + rng.normal(0, 3, size=365)).round(1)

print("shape:", temps.shape)
print("first week:", temps[:7])
print(f"year mean {temps.mean():.2f} C, coldest {temps.min()} C, warmest {temps.max()} C")
print("warmest day index:", temps.argmax())
shape: (365,)
first week: [ 2.3  3.2  1.4 -0.5  0.8 -0.8  2.3]
year mean 11.71 C, coldest -5.4 C, warmest 27.6 C
warmest day index: 204

days - 15 shifts the coldest point of the cosine to mid-January; multiplying by 10 gives a 20-degree swing between winter and summer.

Step 2: Missing readings

Sensors fail. We knock out 12 random days (setting them to NaN), then repair them with linear interpolation between the neighbouring days:

python · try it yourself
import numpy as np

rng = np.random.default_rng(7)
days = np.arange(365)
season = 12 - 10 * np.cos(2 * np.pi * (days - 15) / 365)
temps = (season + rng.normal(0, 3, size=365)).round(1)

raw = temps.copy()
outage = rng.choice(365, size=12, replace=False)       # 12 distinct days
raw[outage] = np.nan
print("missing days:", np.sort(outage))
print("missing count:", np.isnan(raw).sum())
print("naive mean:", np.mean(raw), " nan-aware mean:", np.nanmean(raw).round(2))

ok = ~np.isnan(raw)
clean = raw.copy()
clean[~ok] = np.interp(days[~ok], days[ok], raw[ok]).round(1)
print("after repair, missing:", np.isnan(clean).sum())
print("largest repair error:", np.abs(clean - temps)[outage].max().round(1), "C")
missing days: [ 75  82  87 184 192 244 268 299 336 343 347 350]
missing count: 12
naive mean: nan  nan-aware mean: 11.73
after repair, missing: 0
largest repair error: 6.9 C

Because we kept the true values, we can measure how good the repair is. Interpolation can't predict day-to-day noise, so repair errors of several degrees on single days are expected.

Step 3: Monthly report

Months have different lengths, so we give every day a month number with np.repeat. Then a boolean mask per month selects its days. np.bincount with weights computes all monthly sums in one call:

python · try it yourself
import numpy as np

rng = np.random.default_rng(7)
days = np.arange(365)
season = 12 - 10 * np.cos(2 * np.pi * (days - 15) / 365)
temps = (season + rng.normal(0, 3, size=365)).round(1)

names = np.array(["Jan", "Feb", "Mar", "Apr", "May", "Jun",
                  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])
month_len = np.array([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])
month = np.repeat(np.arange(12), month_len)            # 365 month numbers
print(month[:3], month[-3:], len(month))

means = np.bincount(month, weights=temps) / month_len  # all 12 means at once
print("month  mean   min   max")
for m in range(12):
    t = temps[month == m]
    print(f"{names[m]}   {means[m]:5.1f} {t.min():5.1f} {t.max():5.1f}")

print("warmest month:", names[means.argmax()], " coldest:", names[means.argmin()])
[0 0 0] [11 11 11] 365
month  mean   min   max
Jan     0.8  -5.4   6.1
Feb     3.6  -1.3   9.7
Mar     6.5   0.3  12.4
Apr    11.4   4.6  18.2
May    16.0   8.9  22.1
Jun    19.6  15.3  25.3
Jul    22.7  16.8  27.6
Aug    19.6  15.2  26.2
Sep    16.4   8.4  22.3
Oct    12.5   6.2  19.1
Nov     7.1   2.1  14.0
Dec     3.8  -2.7   9.9
warmest month: Jul  coldest: Jan

Step 4: Detecting heat waves

Let's define a heat wave as 3 or more consecutive days at or above 23 °C. Finding runs in a boolean array is a classic vectorised trick: pad the mask with zeros, take np.diff, and the run starts are where the difference is +1, the ends where it is -1:

python · try it yourself
import numpy as np

rng = np.random.default_rng(7)
days = np.arange(365)
season = 12 - 10 * np.cos(2 * np.pi * (days - 15) / 365)
temps = (season + rng.normal(0, 3, size=365)).round(1)

hot = temps >= 23
print("hot days:", hot.sum())

edges = np.diff(np.concatenate(([0], hot.astype(int), [0])))
starts = np.flatnonzero(edges == 1)
ends = np.flatnonzero(edges == -1)            # one past the last hot day
lengths = ends - starts
print("all hot runs:", lengths)

waves = lengths >= 3
dates = np.datetime64("2025-01-01") + starts[waves]
for d, n, s in zip(dates, lengths[waves], starts[waves]):
    print(f"heat wave from {d}: {n} days, peak {temps[s:s + n].max()} C")
hot days: 22
all hot runs: [1 1 1 1 3 2 4 1 5 1 1 1]
heat wave from 2025-07-06: 3 days, peak 25.3 C
heat wave from 2025-07-14: 4 days, peak 24.8 C
heat wave from 2025-07-21: 5 days, peak 27.6 C

Adding an integer array to a datetime64 value turns day numbers into real dates, which makes the report much friendlier.

Step 5: Unusual days

A day is unusual when it differs a lot from what the season predicts. We compute a 7-day moving average with np.convolve, then flag days more than 2 standard deviations away from it (a z-score):

python · try it yourself
import numpy as np

rng = np.random.default_rng(7)
days = np.arange(365)
season = 12 - 10 * np.cos(2 * np.pi * (days - 15) / 365)
temps = (season + rng.normal(0, 3, size=365)).round(1)

window = np.ones(7) / 7
smooth = np.convolve(temps, window, mode="same")       # same length as temps
resid = temps - smooth
z = (resid - resid.mean()) / resid.std()
odd = np.flatnonzero(np.abs(z) > 2)
print("unusual days:", len(odd))

# The three most extreme, sorted by |z|
top = odd[np.argsort(-np.abs(z[odd]))][:3]
for d in top:
    kind = "warm" if z[d] > 0 else "cold"
    print(f"day {d:3d}: {temps[d]:5.1f} C vs smoothed {smooth[d]:5.1f} C  ({kind}, z = {z[d]:+.2f})")
unusual days: 15
day 277:   6.2 C vs smoothed  13.3 C  (cold, z = -2.81)
day 103:  18.2 C vs smoothed  11.4 C  (warm, z = +2.67)
day 252:  21.9 C vs smoothed  15.1 C  (warm, z = +2.67)

Note: mode="same" keeps the result the same length as the input, but the first and last three days are averaged with zeros beyond the edges, so they look artificially cold. A careful analysis would ignore those edge days or use mode="valid".

Step 6: Chart the year

Finally, one figure shows the daily values, the smoothed curve, the monthly means and the heat waves:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(7)
days = np.arange(365)
season = 12 - 10 * np.cos(2 * np.pi * (days - 15) / 365)
temps = (season + rng.normal(0, 3, size=365)).round(1)

month_len = np.array([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])
month = np.repeat(np.arange(12), month_len)
means = np.bincount(month, weights=temps) / month_len
mid_month = np.cumsum(month_len) - month_len / 2       # x position of each month's centre
smooth = np.convolve(temps, np.ones(7) / 7, mode="valid")   # no edge effects

hot = temps >= 23
edges = np.diff(np.concatenate(([0], hot.astype(int), [0])))
starts, ends = np.flatnonzero(edges == 1), np.flatnonzero(edges == -1)

fig, ax = plt.subplots(figsize=(8, 3.8))
ax.plot(days, temps, color="#4dabcf", linewidth=0.8, alpha=0.7, label="daily")
ax.plot(days[3:-3], smooth, color="#1d3557", linewidth=2, label="7-day average")
ax.plot(mid_month, means, "o", color="#e07a5f", label="monthly mean")
for s, e in zip(starts, ends):
    if e - s >= 3:
        ax.axvspan(s, e, color="#e07a5f", alpha=0.25)
ax.set_xticks(np.cumsum(month_len) - month_len, ["J", "F", "M", "A", "M", "J",
                                                 "J", "A", "S", "O", "N", "D"])
ax.set_ylabel("temperature (C)")
ax.set_title("Weather station, simulated year (shaded: heat waves)")
ax.legend(loc="upper left", fontsize=8)
plt.tight_layout()
plt.show()
print(f"Chart of {len(temps)} days, {len(smooth)} smoothed points, {(ends - starts >= 3).sum()} heat waves")
Chart of 365 days, 359 smoothed points, 3 heat waves

np.convolve(..., mode="valid") returns only the 359 positions where the window fits entirely, so we plot it against days[3:-3] to centre each average on its middle day.

Make it your own

Idea Skills practised
Add a second station with rng.normal(...) and compare them month by month broadcasting, 2-D arrays
Simulate daily rainfall with rng.exponential and mark dry days with rng.random() < p random distributions, masks
Find the longest cold spell (days below 0 °C) the run-detection trick from Step 4
Store each day as a structured record (date, temp, rain) structured arrays
Fit a cosine curve to the data with np.linalg.lstsq and compare with the true season linear algebra
Load the same analysis into pandas with pd.DataFrame moving on to pandas

Test yourself

In Step 3, what does np.repeat(np.arange(12), month_len) produce?

  1. 12 random month numbers
  2. A 365-element array giving the month number of every day
  3. The cumulative month lengths
  4. A 12 x 31 table

Why does Step 4 pad the boolean mask with 0 at both ends before np.diff?

  1. To make the array sortable
  2. So that runs touching the start or end still produce a +1 and a -1 edge
  3. To convert booleans to floats
  4. np.diff requires an even length

Which function repaired the missing readings in Step 2?

  1. np.nanmean
  2. np.interp
  3. np.convolve
  4. np.fill