Skip to content

23. NumPy — Mini-project

You support the facilities team of a server room. Four sensors log temperature, humidity and vibration every 10 minutes. After two weeks, the team asks four questions:

  1. Is the data complete?
  2. Which readings are spikes, and how do they distort the averages?
  3. Is any sensor drifting, and by how many degrees per day?
  4. Is any machine wearing out, and does the status column follow the documented rule?

Write a script, sensor_health.py, that answers these questions with NumPy only: no pandas and no loops over rows. It prints a short report and saves the cleaned temperatures to output/clean_temperature.npy for the next tool in the chain.

The project uses the core of the module: loading with genfromtxt and loadtxt, reshaping to 3 dimensions, boolean masks, broadcasting with keepdims, NaN-aware aggregations over several axes, np.where and np.select, lstsq with several targets at once, and saving arrays. Stretch goal 3 adds sorting and np.unravel_index.

data/sensors.csv: 8,064 rows, 4 sensors × 2,016 ten-minute readings from 2024-05-01 00:00 to 2024-05-14 23:50. The rows are sorted by timestamp and then by sensor_id (S1, S2, S3, S4).

Column Position Content
timestamp 0 ISO date and time
sensor_id 1 S1 to S4
temperature_c 2 float, 22 blank
humidity_pct 3 float, 29 blank
vibration_mm_s 4 float, 30 blank
status 5 ok, warn or fail, never blank

The documented status rule: fail if vibration ≥ 11.2 or temperature ≥ 42; warn if vibration ≥ 4.5 or temperature ≥ 33; otherwise ok. The rule was applied before the blanks were injected.

A day has 144 ten-minute slots, so every measurement fits a (14, 144, 4) array: day, slot, sensor.

Your script must:

  1. Load the three numeric columns into one float array with np.genfromtxt, and the sensor_id and status columns with np.loadtxt(..., dtype=str).
  2. Check that the rows follow the S1–S4 pattern before any reshape, with an assert.
  3. Reshape temperature and vibration to (14, 144, 4).
  4. Report the missing values per sensor for each measurement.
  5. Flag temperature spikes: readings more than 5 °C above the median of the same sensor at the same time of day (the median over the 14 days). Report the count per sensor.
  6. Flag vibration spikes: readings more than 2 times the median of the same sensor on the same day. Report the count per sensor.
  7. Set the temperature spikes to NaN in a copy. Report the mean temperature per sensor before and after.
  8. Measure drift: fit a straight line to the daily mean (clean) temperature of each sensor with one np.linalg.lstsq call, and report the slope in °C per day. Flag the sensors with a slope above 0.1 °C per day.
  9. Measure wear: compare each sensor’s median vibration over the last 3 days with its median over the first 11 days. Flag the sensors where the ratio is above 1.5.
  10. Rebuild the status column from the rule with np.select and report the number of rows that disagree with the file.
  11. Save the clean temperature cube with np.save, load it back and check it with assert.
  12. Print the report below exactly.
Expected output
Sensor health report: 2024-05-01 to 2024-05-14 (14 days x 144 slots x 4 sensors)
Missing temperature: [6 4 6 6]
Missing humidity: [11 8 5 5]
Missing vibration: [10 3 10 7]
Temperature spikes: [ 8 13 11 8] (total 40)
Vibration spikes: [ 7 10 13 11] (total 41)
Mean temp raw: [22.05 24.6 23.53 26.04]
Mean temp clean: [22. 24.52 23.46 25.99]
Drift (degC/day): [-0.001 0.004 0.352 0.001]
Drifting sensors: ['S3']
Vibration ratio: [1.01 1.01 1.01 2.17]
Wearing sensors: ['S4']
Status rule: 8063 of 8064 rows agree
Saved: output/clean_temperature.npy (64,512 bytes of data)
  1. Load. Read columns 2–4 with genfromtxt and columns 1 and 5 with loadtxt. Print the shapes and dtypes once to check, then remove the prints.

  2. Check the layout. Reshape the ids to (-1, 4) and compare them with np.array(["S1", "S2", "S3", "S4"]). Broadcasting does the comparison for every row. Assert that all are equal.

  3. Build the cubes. temperature.reshape(14, 144, 4) and the same for vibration. Remember: axis 0 is the day, axis 1 the slot, axis 2 the sensor.

  4. Count the gaps. np.isnan(...) gives a mask. Sum it over every axis except the sensor axis, or reshape to (-1, 4) and sum over axis 0.

  5. Find temperature spikes. The time-of-day baseline is np.nanmedian(cube, axis=0, keepdims=True), with shape (1, 144, 4). Subtract it from the cube and compare with 5.0.

  6. Find vibration spikes. The daily baseline is the median over axis 1 (the slots) with keepdims=True, shape (14, 1, 4).

  7. Clean and compare. np.where(spike, np.nan, cube) makes a cleaned copy. Compare nanmean over axes 0 and 1 before and after.

  8. Fit the drift. The daily means have shape (14, 4). Build a (14, 2) design matrix [1, day]. np.linalg.lstsq(design, daily_means) accepts a matrix on the right side and fits all 4 sensors at once: the result has shape (2, 4), and row 1 holds the slopes.

  9. Measure wear. Compute the daily median vibration (14, 4), then the median of rows :11 and of rows 11:. Divide.

  10. Check the status rule. Use the flat columns of length 8,064 with np.select, as in the lesson.

  11. Save. Create the output folder with Path("output").mkdir(exist_ok=True). np.save(path, array) writes the binary .npy format, which keeps the shape and dtype; np.load(path) reads it back.

  12. Print the report. Pass precision=3, suppress=True to np.set_printoptions and round the arrays where the report shows 2 decimals.

A skeleton to start from:

sensor_health.py (starter)
# sensor_health.py: a two-week health report for four sensors, NumPy only.
from pathlib import Path
import numpy as np
np.set_printoptions(precision=3, suppress=True)
SENSORS = np.array(["S1", "S2", "S3", "S4"])
DAYS, SLOTS = 14, 144
# --- Load and check ---
# TODO: numeric columns, ids, status; assert the S1-S4 pattern
# --- Cubes and gaps ---
# TODO: temperature and vibration as (DAYS, SLOTS, 4); missing per sensor
# --- Spikes ---
# TODO: time-of-day baseline for temperature, daily baseline for vibration
# --- Drift and wear ---
# TODO: lstsq on daily means; vibration ratio last 3 days / first 11 days
# --- Status rule ---
# TODO: np.select, count agreements
# --- Save and report ---
# TODO: np.save, np.load, assert, print the report
Criterion Points Full points when
Runs as a script 2 python sensor_health.py runs with no error and no warning
Loading and layout check 2 numeric and text columns load with the right readers; an assert checks the S1–S4 pattern
Reshaping 2 the cubes have shape (14, 144, 4) and every reduction uses the right axis
Spikes 3 both baselines use keepdims and broadcasting; the counts match the report
Cleaning 2 spikes become NaN in a copy; the raw data is unchanged
Drift 2 one lstsq call fits all four sensors; S3 is flagged
Wear and status 2 the vibration ratio flags S4; np.select rebuilds the status rule
No row loops 2 no for loop over rows or readings (loops over 4 sensor names for printing are fine)
Output 1 the report equals the expected report; the .npy file reloads
Total 18 15 or more: you are ready for module 24
  1. Add humidity to the report: does S3’s humidity drift too? Fit its slope with the same lstsq call by stacking the daily means of temperature and humidity side by side (shape (14, 8)).
  2. Correct the drift: subtract slope × day from S3’s cleaned temperatures and show that its daily means are flat afterwards.
  3. Print the timestamps of the 5 largest temperature spikes, with their sensor and size. Use np.argsort on the flattened deviations and np.unravel_index.
  4. Fill the remaining gaps of the clean temperature cube with the time-of-day baseline (np.where) and assert that no NaN remains.
  5. Save all three cleaned measurements in one file with np.savez_compressed("output/sensors_clean.npz", temperature=..., humidity=..., vibration=...) and compare the file size with the .npy file.

Try the project yourself first. Then compare your script with this one. Your names can differ; your report must not.

Reference solution
sensor_health.py
# sensor_health.py: a two-week health report for four sensors, NumPy only.
from pathlib import Path
import numpy as np
np.set_printoptions(precision=3, suppress=True)
SENSORS = np.array(["S1", "S2", "S3", "S4"])
DAYS, SLOTS = 14, 144
PATH = "data/sensors.csv"
# --- Load and check ------------------------------------------------------
numeric = np.genfromtxt(PATH, delimiter=",", skip_header=1, usecols=(2, 3, 4))
ids = np.loadtxt(PATH, delimiter=",", skiprows=1, usecols=1, dtype=str)
status = np.loadtxt(PATH, delimiter=",", skiprows=1, usecols=5, dtype=str)
assert (ids.reshape(-1, 4) == SENSORS).all(), "rows are not in S1-S4 order"
temperature, humidity, vibration = numeric.T # three (8064,) columns
# --- Cubes and gaps: (day, slot, sensor) --------------------------------
temp = temperature.reshape(DAYS, SLOTS, 4)
vib = vibration.reshape(DAYS, SLOTS, 4)
missing = np.isnan(numeric).reshape(-1, 4, 3).sum(axis=0) # (sensor, measure)
# --- Spikes ---------------------------------------------------------------
time_of_day = np.nanmedian(temp, axis=0, keepdims=True) # (1, SLOTS, 4)
temp_spike = (temp - time_of_day) > 5.0
daily_vib = np.nanmedian(vib, axis=1, keepdims=True) # (DAYS, 1, 4)
vib_spike = vib > 2.0 * daily_vib
clean = np.where(temp_spike, np.nan, temp) # a new array; temp is unchanged
mean_raw = np.nanmean(temp, axis=(0, 1))
mean_clean = np.nanmean(clean, axis=(0, 1))
# --- Drift: one least-squares fit for all four sensors ----------------------
daily_mean = np.nanmean(clean, axis=1) # (DAYS, 4)
design = np.column_stack([np.ones(DAYS), np.arange(DAYS)]) # (DAYS, 2)
coef = np.linalg.lstsq(design, daily_mean)[0] # (2, 4): intercepts, slopes
slope = coef[1]
# --- Wear: last 3 days against the first 11 ----------------------------------
day_median = np.nanmedian(vib, axis=1) # (DAYS, 4)
ratio = np.median(day_median[11:], axis=0) / np.median(day_median[:11], axis=0)
# --- Status rule ------------------------------------------------------------
rule = np.select(
[
(vibration >= 11.2) | (temperature >= 42),
(vibration >= 4.5) | (temperature >= 33),
],
["fail", "warn"],
default="ok",
)
agree = int((rule == status).sum())
# --- Save -------------------------------------------------------------------
Path("output").mkdir(exist_ok=True)
out_path = Path("output") / "clean_temperature.npy"
np.save(out_path, clean)
reloaded = np.load(out_path)
# --- Report -----------------------------------------------------------------
period = "2024-05-01 to 2024-05-14"
print(f"Sensor health report: {period} ({DAYS} days x {SLOTS} slots x 4 sensors)")
print("Missing temperature:", missing[:, 0])
print("Missing humidity: ", missing[:, 1])
print("Missing vibration: ", missing[:, 2])
temp_counts, vib_counts = temp_spike.sum(axis=(0, 1)), vib_spike.sum(axis=(0, 1))
print("Temperature spikes: ", temp_counts, f"(total {temp_counts.sum()})")
print("Vibration spikes: ", vib_counts, f"(total {vib_counts.sum()})")
print("Mean temp raw: ", mean_raw.round(2))
print("Mean temp clean: ", mean_clean.round(2))
print("Drift (degC/day): ", slope)
print("Drifting sensors: ", SENSORS[slope > 0.1])
print("Vibration ratio: ", ratio.round(2))
print("Wearing sensors: ", SENSORS[ratio > 1.5])
print(f"Status rule: {agree} of {len(status)} rows agree")
print(f"Saved: {out_path.as_posix()} ({reloaded.nbytes:,} bytes of data)")
# --- Self-checks ------------------------------------------------------------
assert temp.shape == (DAYS, SLOTS, 4) and temp_spike.sum() == 40
assert np.isnan(temp).sum() == 22 # the raw cube still has only the real gaps
assert np.array_equal(reloaded, clean, equal_nan=True)
assert SENSORS[slope > 0.1].tolist() == ["S3"]
assert SENSORS[ratio > 1.5].tolist() == ["S4"]
Output
Sensor health report: 2024-05-01 to 2024-05-14 (14 days x 144 slots x 4 sensors)
Missing temperature: [6 4 6 6]
Missing humidity: [11 8 5 5]
Missing vibration: [10 3 10 7]
Temperature spikes: [ 8 13 11 8] (total 40)
Vibration spikes: [ 7 10 13 11] (total 41)
Mean temp raw: [22.05 24.6 23.53 26.04]
Mean temp clean: [22. 24.52 23.46 25.99]
Drift (degC/day): [-0.001 0.004 0.352 0.001]
Drifting sensors: ['S3']
Vibration ratio: [1.01 1.01 1.01 2.17]
Wearing sensors: ['S4']
Status rule: 8063 of 8064 rows agree
Saved: output/clean_temperature.npy (64,512 bytes of data)

Run it from the project folder:

Terminal
python sensor_health.py

How it works:

  1. Load and check. genfromtxt turns the blanks into NaN; loadtxt is enough for the text columns, which have no blanks. The assert compares a (2016, 4) id matrix with the (4,) row of names by broadcasting. If a row were missing, it would fail instead of shifting data silently. numeric.T has shape (3, 8064), so unpacking gives the three columns.
  2. Gaps. np.isnan(numeric) has shape (8064, 3). Reshaping it to (2016, 4, 3) puts the sensor on axis 1 and the measurement on axis 2; summing over axis 0 gives a (4, 3) table of gaps.
  3. Temperature spikes. The median over the days gives the normal temperature of each sensor at each time of day. With keepdims=True its shape (1, 144, 4) broadcasts against (14, 144, 4). The rule finds the 40 spikes of the data dictionary.
  4. Vibration spikes. The daily median follows S4’s rising wear, so wear does not count as a spike. Twice the daily median finds 41 readings, the number of vibration spikes in the data dictionary.
  5. Cleaning. np.where builds a new array, so temp keeps its spikes; the second self-check proves that the raw cube was not changed. A tuple axis=(0, 1) reduces the days and slots together and leaves one mean per sensor.
  6. Drift. lstsq accepts a matrix of targets: each column of daily_mean is fitted separately against the same design matrix, in one call. S3 drifts by 0.352 °C per day, the calibration drift of the data dictionary. The other slopes are close to 0.
  7. Wear. S4’s median vibration over the last 3 days is 2.17 times its earlier level. The ratio is close to 1 for the other sensors.
  8. Status rule. One row disagrees: a warn row whose trigger value is now a blank, so the rule cannot see it.
  9. Save. .npy stores the raw bytes plus the shape and dtype: 14 × 144 × 4 floats × 8 bytes = 64,512 bytes of data. np.array_equal(..., equal_nan=True) treats NaN as equal to NaN, which the default comparison does not. as_posix() prints the path with / on every system.

Alternative: you can keep everything in one 4-D cube, numeric.reshape(DAYS, SLOTS, 4, 3) (day, slot, sensor, measurement), and index the measurement on the last axis: cube[..., 0] is temperature. The ... (ellipsis) means “all the axes before”. It saves the separate reshapes, at the cost of one more axis to keep in your head.