Skip to content
You Start with one site
Amounts in Start with one site
Control, Measurement & Energy · Course

Gaps, Flatlines and Outliers

Lesson 9 of 10 25 min read
Found this useful?

An inspector opens the temperature record of a cold room and finds two hours at 5.09 °C, above the limit of 5.0 °C. The stock is put on hold. The room was never warm: the sensor had stopped answering, and the logger wrote its last value 120 times. On another site the month’s water total is low by a third of a day, because a link failed for six hours and the software added nothing for them. Every real record contains readings that are missing or false, and a calculation treats them like any other reading unless you stop it. This lesson shows how to find the common faults, how to mark them, and what may honestly be said about the period they cover. #DataQuality #MissingData #Outliers

Learning Objectives

By the end of this lesson, you will be able to:

  1. Recognise a gap, a flatline, a spike, a drift, a duplicate and a wrong unit by the sign each leaves in a record
  2. Derive a rate-of-change limit and a flatline rule from the physics of the equipment and the noise of the sensor
  3. Flag faulty readings without deleting them, and state the coverage of what remains
  4. Decide when a gap may be filled, and by which method
  5. Calculate what a gap does to a mean and to a total

Real-World System Problem: A record that passes through four devices



A reading passes through four devices before it reaches a calculation: the sensor makes it, the logger gives it a time, a link carries it and a store keeps it. Each can fail without stopping the others, and each failure leaves a different mark.

A sensor that loses its supply may send nothing, or the logger may repeat the last value it heard. A loose connector adds a single wild reading. A link that drops for three hours leaves a hole, and a link that sends twice leaves two rows for one minute. A change of firmware turns kilowatts into watts.

None of these faults stops a mean or a sum from being calculated, so the check of the data comes before any average.

StoreLinkLoggerSensordriftflatlinegapwrong unitspikeclock errorduplicatewrong scalestuck value
Where each fault enters the record

Fundamental Theory: Finding and treating bad data



Six kinds of bad data

Each kind of fault leaves a sign that a simple rule can test.

FaultSign it leaves in the recordSimple rule
GapTimestamps are missing, or the value is empty (NaN)Time between rows is longer than the interval
FlatlineThe same value repeats exactly, with no noiseA run of identical values longer than noise allows
SpikeOne reading far from both neighbours, then a returnChange in one interval larger than the physics allows
DriftA slow, one-way movement that the process does not explainCompare with a second sensor or a calibration
DuplicateThe same timestamp appears twiceCount rows for each timestamp
Wrong unitA sudden step by a fixed factor (1000, 3.6, or 1.8 with an offset of 32)Ratio of the levels before and after
tempspikeflatline...gap...timenormal cyclesno rowsno noise
Three faults in one temperature trace

Flag first, never delete silently

When a bad reading is found, do not delete the row and do not type a better value over it: nobody could check your decision later. Keep the raw value and add a second column, a flag, that says what was found: good, gap, flatline, spike, filled. If a rule later proves too strict, the flags change and the raw data is still there, as a teacher’s mark in the margin leaves the answer readable.

Coverage

The number expected is the length of the period divided by the logging interval: for 14 days at one reading a minute. Report the coverage with every mean and every total.

Finding a gap

Most files have no empty row for a missing minute: the row is simply absent, and a plot draws a straight line across the hole. So calculate the time between each row and the next; wherever it is longer than the logging interval, readings are missing. Then count: readings expected minus readings received.

Finding a flatline

A real sensor has noise. If the noise has a standard deviation and the logger stores values with a resolution (the smallest step it can write), two readings in a row are equal only when both fall into the same step of width . Even if the measured quantity did not move at all, the chance of that is at most

because is the highest point of the normal curve. The chance of further repeats in a row is at most .

For and , , and four repeats have a chance of at most . Five identical readings in a row are already suspect.

Finding a spike

A room, a tank or a pipe cannot change faster than its physics allows, so a reading that moves faster is not a measurement of the room. The rate-of-change limit has two parts: the largest true change in one interval, and an allowance for the noise of the two readings that are subtracted, which is for their difference.

Here is the largest true change in one interval and is the limit. A spike is a reading that departs by more than and returns by more than at the next reading. A single jump that does not return is a step, which may be real (a door left open) or the end of another fault.

The second test is the running median. Take each reading with the two before it and the two after it, and find the median of the five. One wild value among five cannot move a median (a mean would move by one fifth of it), so the spike stands far from the median. Flag a reading whose distance from the running median is above a threshold that the clean signal never reaches.

Neither test finds a small spike. A false reading that is 0.3 °C high looks the same as a door opening.

Drift, duplicates and wrong units

A drift cannot be proved from the drifting channel alone, because a slow real change looks the same. It needs a reference: a second sensor or a calibration. The test of a slope against zero is in finding a step and a drift.

A duplicate hardly changes a mean and doubles its interval in a sum, so count the rows for each timestamp before adding. Look at the values before you delete one of a pair. Two equal rows are a duplicate. Two different rows at the same local time on the night that clocks go back are two real hours, and the fix is to convert the times to UTC, not to delete.

Before any of these rules, apply a range check: a reading outside what the sensor can measure, or outside what the room can reach, is flagged at once. Learn the values a sensor sends when it fails. A DS18B20 temperature sensor reads 85.0 °C before its first conversion, a common Arduino library returns °C for a sensor that does not answer, and a 4 to 20 mA loop below about 3.6 mA or above about 21 mA is a failed loop (NAMUR NE 43), not a value. A wrong unit shows as a step by a known factor: a power channel that moves from about 2.4 to about 2,400 has changed from kW to W.

What a gap does to a mean and to a sum

A mean of the remaining readings is still a fair estimate if the gap fell at random. It is biased if the gap fell where the signal is unlike the rest, for example in the working hours of a room that is warmer by day.

A sum is always low. Adding the remaining readings is the same as treating every missing reading as zero.

A total across a gap

A total with a gap in it is a lower bound. State it as “at least”, with the hours covered.

Honest filling

Filling a gap with an estimate is called imputation. It is honest when the estimate is good and the filled values are flagged as filled.

  • A short gap in a slow signal. Draw a straight line between the readings on each side (linear interpolation). “Short” means short against the time the signal needs to change: a few minutes for a room, an hour for a large tank.
  • A gap in a signal with a daily pattern. Fill each missing hour with the typical value for that hour, from the profile of the other days, and state the uncertainty of the fill.
  • Energy or volume across a long gap. Never interpolate power and add it. A meter that totalises (kWh or m³) keeps counting when the link is down, as a car’s odometer knows the distance when the speed log is lost, and the difference of its counter before and after the gap is the true total.
  • Anything else. Leave it empty and report the coverage.

Application 1: A cold room record with three kinds of fault



Step 1: Know the clean record

Click to reveal what a healthy record looks like
  1. Round to the resolution. After rounding to 0.01 °C the mean is still 4.013 °C. The time above 5.0 °C is 842 minutes, 4.18 percent. Before rounding it was 877 minutes, 4.35 percent: 35 readings just above 5.000 became exactly 5.00. A count against a limit depends on the resolution of the logger. ✅

  2. Largest true change in a minute. The fastest rise is warming with the door open, and the fastest fall is the compressor running with the door closed.

    The room cannot change by more than 0.45 °C in one minute. ✅

  3. What the readings show. The largest rise between two readings of the clean record is 0.68 °C and the largest fall is 0.58 °C. Both pass the physical limit, because each reading carries its own noise. A limit of 0.45 °C on every change would flag 191 good readings. The longest run of identical readings is 2. ✅

Step 2: The gap

Click to reveal the gap rule and its result
  1. Rule. A reading is missing if its timestamp is absent or its value is NaN. In this script the rows exist and hold NaN. In a file where the rows are absent, the time from reading 9,239 to the next row would be 181 minutes in place of 1. ✅

  2. Result. The rule finds 180 of the 180 missing readings, with no false alarm. ✅

  3. Coverage after the gap. percent. The gap is 0.9 percent of the record. ✅

Step 3: The flatline

Click to reveal the flatline rule and its result
  1. Chance of one repeat. With a noise of 0.05 °C and a resolution of 0.01 °C,

    Even in a room that stood perfectly still, a reading would repeat the one before it less than 8 times in 100. ✅

  2. Chance of a run. Five identical readings need four repeats: at most . For 120 identical readings (119 repeats) the bound is . This room also moves by at least 0.10 °C every minute, so the true chances are smaller still. ✅

  3. Rule. Flag a run of 5 or more identical readings as a flatline. Do not flag the first reading of the run: it was the last real measurement. ✅

  4. Result. The rule finds 120 of the 120 stuck readings, all at 5.09 °C, with no false alarm on the clean record. ✅

Step 4: The spikes

Click to reveal the two spike rules and their results
  1. Rate-of-change limit. Add the noise allowance to the largest true change.

    Use a limit of 0.75 °C a minute. The largest change in the clean record, 0.68 °C, is below it. ✅

  2. Rate rule. Flag a reading that differs from the one before it by more than 0.75 °C and from the one after it by more than 0.75 °C, in opposite directions. At 11:45 on day 3 the reading is 8.13 °C: it rises by 3.13 °C and falls by 3.29 °C in the next minute. ✅

  3. Median rule. In the clean record no reading is further than 0.56 °C from its 5-point running median. Flag a reading that is more than 1.0 °C from the running median. The five spikes stand 2.59 to 3.27 °C from it. ✅

  4. Result. Each rule finds 5 of the 5 spikes and raises no false alarm, on the damaged record or on the clean one. With a limit of 0.45 °C and no noise allowance, the rate rule also flags 2 good readings of the clean record. ✅

  5. The end of the flatline. When the stuck sensor returns, the reading moves from 5.09 to 3.72 °C in one minute. This is one jump with no return, so the spike rule leaves this good reading unflagged. ✅

Step 5: Effect on the statistics

Click to reveal the three sets of statistics
  1. Calculate each statistic three times. “Ignored” means that every number in the file is used as it stands and NaN is skipped, as most software does.

    CaseReadings usedMean (°C)Above 5.0 °CMaximum (°C)Longest run above 5.0 °C
    True record20,1604.0134.18 %5.443 min
    Damage ignored19,9804.0204.75 %8.13122 min
    Flagged and excluded19,8554.0134.16 %5.443 min

    ✅

  2. Read the mean. The damage moves the mean by 0.007 °C. A mean of 20,000 readings is hard to move: 120 readings about 1.1 °C too high add °C. ✅

  3. Read the limit statistics. The time above 5.0 °C rises from 842 to 950 minutes. The maximum becomes 8.13 °C, which is a spike and not a temperature. The longest run above 5.0 °C becomes 122 minutes in place of 3: two real readings above the limit and 120 copies of the second. An inspector who reads this number sees a failed room. ✅

  4. After flagging. The rules flag readings, so the coverage is percent. The maximum and the longest run return to their true values, and the time above the limit is 4.16 percent against a true 4.18 percent. ✅

  5. Check a second way. The 305 excluded minutes held 17 true minutes above 5.0 °C (10 in the gap, 6 in the flatline, 1 at a spike). So minutes remain, which is 4.16 percent of 19,855. Flagging removes the false readings. It cannot return the true ones. ✅

Application 2: A day of borehole flow with six hours missing



Step 1: Three treatments of the same day

Click to reveal the three volumes
  1. Gap treated as zero. Add the 18 readings that exist.

    This is what a plain sum gives. The lowest of the other 34 days is 71.8 m³. ✅

  2. Gap filled from the profile. The mean flow of the other 34 days at hours 12 to 17 is 4.42, 4.70, 4.46, 4.48, 4.61 and 4.56 m³/h, which add to 27.2 m³.

    (The script keeps all digits. The rounded parts add to 77.7.) ✅

  3. Uncertainty of the fill. At these hours one reading varies by 0.54 m³/h (standard deviation) from day to day. For six independent hours the standard uncertainty is m³ and the expanded uncertainty is 2.7 m³. The filled value is m³. The assumes that one hour tells nothing about the next. On a real site a busy afternoon is often busy in every hour; if the six hours move together, the standard uncertainty is up to m³, and the expanded uncertainty 6.5 m³. Check the correlation of neighbouring hours in the other days before you choose. ✅

  4. Reported as incomplete. “Day 12: 50.5 m³ in 18 of 24 hours. Hours 12:00 to 18:00 not recorded.” Nothing is invented. ✅

  5. Scaling by the coverage. The mean rate of the 18 hours times 24 is m³, which is 13 percent low. The missing hours are all day hours at about 4.5 m³/h, and 8 of the 18 hours seen are night hours at 0.6 m³/h. Scaling is fair only when the missing hours are like the hours seen. ✅

Step 2: Which is honest, and what a counter gives

Click to reveal the comparison
  1. The truth. The data is generated, so the true volume of day 12 is known: 77.5 m³, of which 27.0 m³ passed in the six lost hours. ✅

  2. Errors. Zero: m³, which is percent. Profile fill: percent, inside its stated uncertainty of 2.7 m³. ✅

  3. Effect on the period. The mean daily volume of days 0 to 34 is 77.55 m³. With day 12 at 50.5 m³ it becomes 76.78 m³, 1.0 percent lower. ✅

  4. Which is honest. Treating the gap as zero is false: it states that the pump delivered nothing for six hours. Reporting the day as incomplete is always honest. The profile fill is honest only when it is marked as an estimate with its uncertainty, and when the day was ordinary. If the link failed because the pump failed, the fill invents 27 m³ of water that never flowed. ✅

  5. Check with a counter. A totalising meter reads 933.0 m³ at the end of day 11 and 1,010.5 m³ at the end of day 12.

    The counter gives the true volume with no estimate, because it counted during the gap. It cannot say how the 27.0 m³ was spread over the six hours. ✅

flow rate▄▄▄▄▄▄▄▄ ? ? ? ? ? ? ▄▄▄▄▄▄▄(m3/h)loggedgaploggedcounter933.01010.5(m3)beforegapaftertotal for the day = 77.5 m3
A rate is lost in a gap. A counter is not.

Verify It in Python



The script generates data sets A and C, damages them as stated, applies the rules, and prints every number used above. It saves one figure.

gaps_flatlines_outliers.py
"""Gaps, flatlines and spikes: damage two records in a known way, then find the faults."""
import numpy as np
import matplotlib.pyplot as plt
def cold_room_minutes(seed=11, days=14):
rng = np.random.default_rng(seed)
n = days * 1440
t = np.empty(n); temp = 4.0; on = False; out = []
for i in range(n):
minute = i % 1440
# door openings are more likely in working hours
door = (480 <= minute < 1020) and (rng.random() < 0.035)
if temp >= 5.0: on = True
if temp <= 3.0: on = False
temp += (-0.30 if on else 0.10) + (0.35 if door else 0.0)
t[i] = temp + rng.normal(0.0, 0.05) # sensor noise, 0.05 °C
return t
def borehole_hourly(seed=37, days=60):
rng = np.random.default_rng(seed)
h = np.arange(days * 24); hour = h % 24
demand = np.where((hour >= 6) & (hour < 22), 4.6, 0.6) # m3/h drawn by users
demand = demand * (1.0 + rng.normal(0, 0.12, h.size))
leak = np.where(h >= 35 * 24, 0.9, 0.0) # a leak starts on day 35
flow = np.clip(demand + leak, 0, None) # m3/h
kwh_per_m3 = 0.42 + 0.0006 * (h / 24.0) # slow wear: rising
power = flow * kwh_per_m3 * (1.0 + rng.normal(0, 0.03, h.size)) # kW
return h, flow, power
def run_lengths(x):
"""For each reading, the length of the run of identical values it belongs to."""
n = x.size
start = np.r_[True, x[1:] != x[:-1]] # NaN never equals NaN: run of 1
idx = np.flatnonzero(start)
lengths = np.diff(np.r_[idx, n])
return np.repeat(lengths, lengths), start
def running_median(x, window=5):
"""Centred running median that skips NaN. The ends use a shorter window."""
k = window // 2
pad = np.r_[np.full(k, np.nan), x, np.full(k, np.nan)]
win = np.column_stack([pad[j:j + x.size] for j in range(window)])
out = np.full(x.size, np.nan)
ok = ~np.all(np.isnan(win), axis=1)
out[ok] = np.nanmedian(win[ok], axis=1)
return out
def longest_run(mask):
best = cur = 0
for v in mask:
cur = cur + 1 if v else 0
best = max(best, cur)
return best
def find_faults(x, rate_limit=0.75, run_limit=5, median_limit=1.0):
"""Return four masks: gap, flatline, spike by rate, spike by median."""
gap = np.isnan(x)
length, start = run_lengths(x)
flat = (length >= run_limit) & ~start # the first of a run was a real reading
d = np.diff(x)
rate = np.zeros(x.size, bool) # a jump away and a jump back
with np.errstate(invalid="ignore"): # a comparison with NaN is False
rate[1:-1] = (np.abs(d[:-1]) > rate_limit) & (np.abs(d[1:]) > rate_limit) \
& (d[:-1] * d[1:] < 0)
med = np.abs(x - running_median(x)) > median_limit
return gap, flat, rate, med
def describe(name, x):
good = x[~np.isnan(x)]
print(f" {name:<28s} n {good.size:5d} mean {good.mean():.3f} "
f"above 5.0: {100 * (good > 5.0).mean():.2f} % max {good.max():.2f} "
f"longest run above 5.0: {longest_run(np.nan_to_num(x) > 5.0)} min")
# ---------- Part 1: data set A, the cold room ----------
raw = cold_room_minutes()
clean = np.round(raw, 2) # the logger stores 0.01 degC
print("Cold room, 20160 readings")
print(f" unrounded: mean {raw.mean():.3f}, above 5.0 degC {int((raw > 5.0).sum())} min "
f"({100 * (raw > 5.0).mean():.2f} %)")
print(f" rounded to 0.01: mean {clean.mean():.3f}, above 5.0 degC "
f"{int((clean > 5.0).sum())} min ({100 * (clean > 5.0).mean():.2f} %)")
GAP = 6 * 1440 + 600 # day 6, 10:00, 180 minutes
FLAT = 9 * 1440 + 522 # day 9, 08:42, 120 minutes
SPIKES = np.array([1 * 1440 + 200, 3 * 1440 + 705, 7 * 1440 + 970,
11 * 1440 + 1350, 12 * 1440 + 545])
bad = clean.copy()
bad[GAP:GAP + 180] = np.nan
bad[FLAT:FLAT + 120] = bad[FLAT - 1] # stuck at the last good value
bad[SPIKES] += 3.0
truth_gap = np.zeros(bad.size, bool); truth_gap[GAP:GAP + 180] = True
truth_flat = np.zeros(bad.size, bool); truth_flat[FLAT:FLAT + 120] = True
truth_spike = np.zeros(bad.size, bool); truth_spike[SPIKES] = True
print(f" flatline value {bad[FLAT]:.2f} degC; true mean of those 120 min "
f"{clean[FLAT:FLAT + 120].mean():.2f}")
# what the clean record looks like to each rule
d = np.diff(clean)
length, _ = run_lengths(clean)
print("Clean record, before any damage")
print(f" minute-to-minute change: largest rise {d.max():.2f}, largest fall {d.min():.2f}")
print(f" changes beyond +0.45 or -0.30 (physics alone): "
f"{int(((d > 0.45) | (d < -0.30)).sum())}")
print(f" longest run of identical readings: {length.max()} "
f"(pairs: {int((length == 2).sum() // 2)})")
print(f" largest distance from the 5-point median: "
f"{np.abs(clean - running_median(clean)).max():.2f}")
p_bin = 0.01 / (0.05 * np.sqrt(2 * np.pi))
print(f" chance that one reading repeats the last, at most: {p_bin:.4f}")
print(f" chance of 4 repeats: {p_bin ** 4:.1e}; of 119 repeats: 10^"
f"{119 * np.log10(p_bin):.0f}")
print("Detection (found of injected, false alarms on damaged, false alarms on clean)")
g, f, r, m = find_faults(bad)
cg, cf, cr, cm = find_faults(clean)
for name, found, truth, c in (("gap (NaN)", g, truth_gap, cg),
("flatline (run >= 5)", f, truth_flat, cf),
("spike (rate, 0.75)", r, truth_spike, cr),
("spike (median, 1.0)", m, truth_spike, cm)):
print(f" {name:<22s} {int((found & truth).sum()):3d} of {int(truth.sum()):3d}, "
f"{int((found & ~truth).sum())}, {int(c.sum())}")
_, _, r45, _ = find_faults(bad, rate_limit=0.45)
_, _, c45, _ = find_faults(clean, rate_limit=0.45)
print(f" spike rule with a limit of 0.45: {int((r45 & truth_spike).sum())} of 5, "
f"false alarms on clean {int(c45.sum())}")
plain = np.r_[False, np.abs(np.diff(clean)) > 0.45]
print(f" any single change beyond 0.45, clean record: {int(plain.sum())} flags")
after = FLAT + 120
print(f" step when the flatline ends: {bad[after] - bad[after - 1]:+.2f} degC "
f"(one jump, not a spike)")
print("Effect on the statistics")
flagged = g | f | r | m
kept = np.where(flagged, np.nan, bad)
describe("true (clean record)", clean)
describe("damage ignored", bad)
describe("faults flagged and excluded", kept)
print(f" flagged {int(flagged.sum())} of {bad.size} readings; coverage "
f"{100 * (1 - flagged.mean()):.2f} %")
alt = clean.copy() # the same fault 318 minutes later
ALT = 9 * 1440 + 840 # day 9, 14:00
alt[ALT:ALT + 120] = alt[ALT - 1]
print(f" a flatline from 14:00 instead sticks at {alt[ALT]:.2f} degC and hides "
f"{int((clean[ALT:ALT + 120] > 5.0).sum())} real minutes above 5.0")
describe("flatline at 14:00 only", alt)
# ---------- Part 2: data set C, a 6-hour gap in the flow ----------
h, flow, power = borehole_hourly()
table = flow.reshape(60, 24)
DAY, H0, H1 = 12, 12, 18 # hours 300 to 305 are day 12, 12:00 to 18:00
missing = np.zeros(24, bool); missing[H0:H1] = True
true_day = table[DAY].sum()
seen = table[DAY][~missing].sum()
others = np.delete(table[:35], DAY, axis=0) # the other 34 days before the leak
profile = others.mean(axis=0)
filled = seen + profile[missing].sum()
sd_hour = others[:, missing].std(ddof=1).mean()
u_fill = sd_hour * np.sqrt(missing.sum())
print("Borehole, day 12 with hours 300 to 305 missing")
print(f" true volume of day 12: {true_day:.1f} m3 (hours lost: "
f"{table[DAY][missing].sum():.1f} m3)")
print(f" gap treated as zero: {seen:.1f} m3 ({100 * (seen / true_day - 1):+.1f} %)")
print(f" gap filled from the profile: {seen:.1f} + {profile[missing].sum():.1f} = "
f"{filled:.1f} m3 ({100 * (filled / true_day - 1):+.1f} %)")
print(f" one hour varies by {sd_hour:.2f} m3/h, so the fill is uncertain by "
f"{u_fill:.1f} m3 (standard), {2 * u_fill:.1f} m3 (expanded)")
print(f" reported as incomplete: {seen:.1f} m3 in {int((~missing).sum())} of 24 hours")
print(f" mean rate of the hours seen x 24: {seen / 18 * 24:.1f} m3 "
f"({100 * (seen / 18 * 24 / true_day - 1):+.1f} %)")
days35 = table[:35].sum(axis=1)
zero35 = days35.copy(); zero35[DAY] = seen
print(f" mean daily volume, days 0 to 34: true {days35.mean():.2f}, with the gap "
f"as zero {zero35.mean():.2f}, without day 12 {np.delete(days35, DAY).mean():.2f} m3")
print(f" lowest daily volume of the other 34 days: {np.delete(days35, DAY).min():.1f} m3")
counter = np.cumsum(flow) # a totalising meter, m3
print(f" counter at the end of day 11: {counter[DAY * 24 - 1]:.1f} m3, "
f"end of day 12: {counter[DAY * 24 + 23]:.1f} m3, "
f"difference {counter[DAY * 24 + 23] - counter[DAY * 24 - 1]:.1f} m3")
# ---------- Plot ----------
fig, ax = plt.subplots(2, 1, figsize=(8, 7))
t = np.arange(bad.size) / 1440.0
ax[0].plot(t, bad, linewidth=0.5, label="damaged record")
for mask, mark, name in ((f, "s", "flatline"), (r | m, "o", "spike")):
ax[0].plot(t[mask], bad[mask], mark, markersize=3, label=name)
ax[0].axvspan(GAP / 1440.0, (GAP + 180) / 1440.0, alpha=0.3, label="gap")
ax[0].axhline(5.0, color="gray", linewidth=0.8)
ax[0].set_xlabel("day")
ax[0].set_ylabel("air temperature (degC)")
ax[0].set_title("Cold room: flagged readings")
ax[0].legend(loc="upper right", ncol=4, fontsize=8)
hours = np.arange(24)
shown = np.where(missing, np.nan, table[DAY])
ax[1].step(hours, profile, where="mid", label="profile of the other 34 days")
ax[1].step(hours, shown, where="mid", label="day 12 as logged")
ax[1].plot(hours[missing], table[DAY][missing], "x", label="day 12, the lost hours")
ax[1].set_xlabel("hour of day")
ax[1].set_ylabel("flow (m3/h)")
ax[1].set_title("Borehole: day 12 with six hours missing")
ax[1].legend(fontsize=8)
fig.tight_layout()
fig.savefig("gaps_flatlines_outliers.png", dpi=120)
print("Saved gaps_flatlines_outliers.png")

Expected output

Cold room, 20160 readings
unrounded: mean 4.013, above 5.0 degC 877 min (4.35 %)
rounded to 0.01: mean 4.013, above 5.0 degC 842 min (4.18 %)
flatline value 5.09 degC; true mean of those 120 min 3.98
Clean record, before any damage
minute-to-minute change: largest rise 0.68, largest fall -0.58
changes beyond +0.45 or -0.30 (physics alone): 2663
longest run of identical readings: 2 (pairs: 299)
largest distance from the 5-point median: 0.56
chance that one reading repeats the last, at most: 0.0798
chance of 4 repeats: 4.1e-05; of 119 repeats: 10^-131
Detection (found of injected, false alarms on damaged, false alarms on clean)
gap (NaN) 180 of 180, 0, 0
flatline (run >= 5) 120 of 120, 0, 0
spike (rate, 0.75) 5 of 5, 0, 0
spike (median, 1.0) 5 of 5, 0, 0
spike rule with a limit of 0.45: 5 of 5, false alarms on clean 2
any single change beyond 0.45, clean record: 191 flags
step when the flatline ends: -1.37 degC (one jump, not a spike)
Effect on the statistics
true (clean record) n 20160 mean 4.013 above 5.0: 4.18 % max 5.44 longest run above 5.0: 3 min
damage ignored n 19980 mean 4.020 above 5.0: 4.75 % max 8.13 longest run above 5.0: 122 min
faults flagged and excluded n 19855 mean 4.013 above 5.0: 4.16 % max 5.44 longest run above 5.0: 3 min
flagged 305 of 20160 readings; coverage 98.49 %
a flatline from 14:00 instead sticks at 3.37 degC and hides 4 real minutes above 5.0
flatline at 14:00 only n 20160 mean 4.009 above 5.0: 4.16 % max 5.44 longest run above 5.0: 3 min
Borehole, day 12 with hours 300 to 305 missing
true volume of day 12: 77.5 m3 (hours lost: 27.0 m3)
gap treated as zero: 50.5 m3 (-34.8 %)
gap filled from the profile: 50.5 + 27.2 = 77.8 m3 (+0.3 %)
one hour varies by 0.54 m3/h, so the fill is uncertain by 1.3 m3 (standard), 2.7 m3 (expanded)
reported as incomplete: 50.5 m3 in 18 of 24 hours
mean rate of the hours seen x 24: 67.4 m3 (-13.1 %)
mean daily volume, days 0 to 34: true 77.55, with the gap as zero 76.78, without day 12 77.55 m3
lowest daily volume of the other 34 days: 71.8 m3
counter at the end of day 11: 933.0 m3, end of day 12: 1010.5 m3, difference 77.5 m3
Saved gaps_flatlines_outliers.png

In the upper plot the five spikes stand above the band of the room, the flatline is a level line on day 9, and the shaded strip on day 6 is the gap.

Common Mistakes



  • Deleting bad rows from the file. Keep the raw value and add a flag, so that the decision can be checked.
  • Adding up a record without counting its rows. A sum with a gap is low by what passed during the gap.
  • Setting a spike limit by eye. Take it from the largest change the equipment can make in one interval, plus a noise allowance.
  • Interpolating power across a long gap and calling the result energy. Use the counter, or report the period as incomplete.
  • Reporting a mean or a total without its coverage.

Summary



  • Six faults are common: gap, flatline, spike, drift, duplicate and wrong unit. Each leaves a sign that a simple rule can test.
  • Flag faulty readings, keep the raw values, and state the coverage with every result.
  • A flatline rule comes from the noise and the resolution, and a spike rule from the fastest change the physics allows: 0.45 °C a minute for the cold room, 0.75 °C with the noise allowance.
  • In data set A the faults moved the mean by 0.007 °C and made the longest run above 5.0 °C read 122 minutes in place of 3.
  • A total across a gap is a lower bound. In data set C six lost hours removed 34.8 percent of a day’s volume, a profile fill came within 0.3 percent, and a counter gave the exact value.

Exercises



1. A logger takes one reading a minute for 30 days. The file holds 41,904 rows, with no duplicates. Find the coverage and the total time missing.

Answer

Expected: rows. Coverage: percent. Missing: 1,296 minutes, which is 21.6 hours.

2. A tank holds 500 kg of water and has a 6 kW heater. The specific heat of water is 4,186 J/(kg·K). The sensor noise is 0.05 °C and readings are one minute apart. Find the largest true rise in a minute and a rate-of-change limit with an allowance of four standard deviations of the difference of two readings.

Answer

Rate: K/s, which is 0.172 °C a minute. Allowance: °C. Limit: , so about 0.46 °C a minute. A reading that rises by 2 °C and returns in the next minute is a spike.

3. The hourly mean power of a workshop is logged. On one day the five hours from 09:00 to 14:00 are missing, and the other 19 hours add to 150 kWh. On other days the power at those five hours is about 12 kW. The energy counter read 48,210.4 kWh at the start of the day and 48,418.9 kWh at the end. Find the day’s energy with the gap as zero, filled from the usual power, scaled up by the coverage, and from the counter.

Answer

Zero: 150 kWh. Filled: kWh. Scaled: kWh. Counter: kWh, which is the true value. The gap as zero is 28 percent low, the scaled value 9 percent low, and the fill 0.7 percent high.

4. A room has a mean temperature of 4.0 °C in the 16 hours outside working time and 4.6 °C in the 8 working hours. In one week of hourly data, the 8 working hours of three days are missing. Find the true weekly mean, the mean of the readings that remain, and a method that removes the bias.

Answer

True: °C. Remaining: 112 hours at 4.0 and 32 hours at 4.6, so °C, which is 0.07 °C low. Remedy: take the mean at each hour of the day first (the profile), then the mean of the 24 profile values.

References



  • R. J. Hyndman and G. Athanasopoulos, Forecasting: Principles and Practice, 3rd edition, OTexts, 2021. Free at otexts.com/fpp3 (section on dealing with outliers and missing values).
  • R. J. A. Little and D. B. Rubin, Statistical Analysis with Missing Data, 3rd edition, Wiley, 2019.
  • J. W. Tukey, Exploratory Data Analysis, Addison-Wesley, 1977 (running medians and resistant summaries).
  • D. C. Montgomery and G. C. Runger, Applied Statistics and Probability for Engineers, 7th edition, Wiley, 2018.


© 2021-2026 SiliconWit®. All rights reserved.
Sensor drift spike stuck value Logger flatline clock error Link gap duplicate Store wrong unit wrong scale Under each device: the faults that enter the record there
Where each fault enters the record
3 4 5 6 7 temp, °C time spike gap flatline normal cycles no rows no noise normal example
Three faults in one temperature trace
? ? ? ? ? ? 00 06 12 18 24 h flow rate (m³/h) logged gap logged counter (m³) 933.0 1,010.5 before counts through the gap after total for the day = 1,010.5 − 933.0 = 77.5 m³
A rate is lost in a gap. A counter is not.
Predict first

In a 14-day record of a cold room, one reading a minute, a sensor stops answering and the logger repeats its last value, 5.09 °C, for two hours. Which number in the report changes most?

timeraw valueflag (added) 11:434.62 11:444.65 11:458.13 11:464.84 10:00 ...(no rows) 08:435.09 goodgoodgood spikegapflatline Change a flag later; the raw data is still there.
See it: where to set the spike limit

Spikes found
False alarms in 14 days
Limit L

A cold room made in the page by the lesson's model, 14 days at one reading a minute, with five false readings added at the lesson's times. A reading is flagged when it departs from the one before by more than L and returns by more than L. The lesson's limit is the largest true change, 0.45 °C a minute, plus 4 × 0.05 × √2 = 0.28 °C for the noise of two readings. No limit separates a spike that is as small as the room's own moves.

Watch it build: six lost hours
0006121824 h ? 18 of 24 hours: mean 2.81 0 logged: at least 50.5 m³ straight line: 73.1 m³ profile fill: 77.8 ± 2.7 m³ counter: 1,010.5 − 933.0 = 77.5
  1. Day 12: hours 12:00 to 18:00 are lost. The 18 hours left average 2.81 m³/h; the true mean is 3.23.
  2. Adding what was logged gives 50.5 m³. The lost hours count as zero, so this is a lower bound.
  3. A straight line across six busy hours gives 73.1 m³, still 4.4 m³ short of the truth.
  4. The other 34 days give each lost hour its typical flow: 50.5 + 27.2 = 77.8 ± 2.7 m³.
  5. A counter kept counting through the gap: 1,010.5 − 933.0 = 77.5 m³, the true volume.
flow ratecounter ?????? 6 hours lost 933.01,010.5 77.5 m³ for the day The rate is lost in a gap. The counter is not.

Check yourself

Three questions. Each wrong choice is a mistake people really make, so read the note after you answer.

1. A tank temperature can change by at most 0.2 °C in one logging interval, and the sensor noise is 0.1 °C. What rate-of-change limit do you use for spikes?

2. An energy channel is logged as hourly power. On one day 4 of the 24 hours are missing, and the 20 logged hours add to 1,800 kWh. There is no counter. What do you report for the day?

3. A room sensor has a resolution of 0.5 °C and a noise of 0.05 °C. At night it shows the same value for 40 minutes. Is that a flatline fault?

Found this useful?

Discussion

    Comments show your name. Be kind, stay on the topic.