# Q-12: Find and mark the missing values without deleting anything

Data-Driven Athletics tutorial · Week 4 · Chapter 4 · about 20 min · workflow steps: Gather, Statistics, Visualize, Cleanse

Web page: https://apopt.com/course/tutorials/q12-missing-values/ · Data: https://apopt.com/data/tutorials/q12-missing-values/

## The decision

A runner wants an average contact time for a run. Before averaging, decide which values are not
measurements at all, mark them with a reason, and keep every row so nothing else is lost.

## The raw data

- `raw/2026-05-11_1507_running.csv`: one second-by-second record of a 10.5 km run (3,746 rows, 12 columns) with empty cells, zero codes and pauses The instructor's own run on 11 May 2026, from the course case file `athletes/jh/watch/records/`, published under his name.

### Mark, don't delete

A missing value can hide in three places: an empty cell, a code that stands for "no value" (a 0
where 0 is impossible), and a row that was never written (a gap in the time stamps). Deleting
rows that hold one bad cell throws away the good cells beside it, and deleting a value you do
not understand may throw away the event you were looking for (Section 4.3). So **mark** every
missing value, say why, and keep every row.

The file is the instructor's 11 May 2026 run from Q-11, one row a second, and the rules come from
the dictionary written there.

*Predict first:* How many pauses (gaps of more than 2 s between rows) do you expect in a 94-minute run with 62 minutes moving?

```python
import numpy as np
import pandas as pd

run = pd.read_csv("raw/2026-05-11_1507_running.csv")
t = pd.to_datetime(run["time"], utc=True)
gap = t.diff().dt.total_seconds()
print(f"{len(run)} rows; empty cells: {int(run.isna().sum().sum())}")
print(f"stance time written as 0: {int((run['stance_time_ms'] == 0).sum())}; "
      f"vertical bounce written as 0: {int((run['vertical_oscillation_mm'] == 0).sum())}")
pauses = gap[gap > 2]
print(f"{len(pauses)} gaps over 2 s, {pauses.sum() / 60:.1f} min in all; longest {pauses.max() / 60:.1f} min")
```

Output:

```
3746 rows; empty cells: 4074
stance time written as 0: 574; vertical bounce written as 0: 525
21 gaps over 2 s, 31.9 min in all; longest 13.3 min
```

### Rules first, then a marked copy

The rules, written before they are applied:

1. An empty cell is missing, reason `empty`.
2. A stance time or vertical bounce of 0 is missing, reason `zero code` (the watch made no estimate).
3. A stance time outside 100 to 400 ms is kept and flagged, reason `outside range`: it may be
   an error, or it may be the stride you care about.
4. A gap in time is recorded on the row after it (`gap_before_s`); no rows are invented.

The marked copy has the same rows as the raw file, the codes replaced by empty values, and one
reason column per field.

```python
marked = run.copy()
log = []
for col in run.columns.drop("time"):
    reason = pd.Series("", index=run.index)
    reason[run[col].isna()] = "empty"
    if col in ("stance_time_ms", "vertical_oscillation_mm"):
        reason[run[col] == 0] = "zero code"
        marked.loc[run[col] == 0, col] = np.nan
    if col == "stance_time_ms":
        reason[(run[col] > 0) & ~run[col].between(100, 400)] = "outside range"
    marked[f"{col}_flag"] = reason
    for r, n in reason[reason != ""].value_counts().items():
        log.append({"field": col, "reason": r, "rows": int(n)})
marked["gap_before_s"] = gap.where(gap > 2, 0).fillna(0)
assert len(marked) == len(run)                                  # nothing deleted
import os
os.makedirs("clean", exist_ok=True)
marked.to_csv("clean/run_marked.csv", index=False)
pd.DataFrame(log).to_csv("clean/missing_log.csv", index=False)
print(pd.DataFrame(log).to_string(index=False))
print(f"rows in: {len(run)}, rows out: {len(marked)}")
```

Output:

```
                  field        reason  rows
              speed_mps         empty    37
         heart_rate_bpm         empty     1
            cadence_spm         empty    39
             altitude_m         empty   101
                power_w         empty    39
         stance_time_ms     zero code   574
         stance_time_ms         empty    37
         stance_time_ms outside range    24
vertical_oscillation_mm     zero code   525
vertical_oscillation_mm         empty    37
         step_length_mm         empty    37
          temperature_c         empty  3746
rows in: 3746, rows out: 3746
```

Every row is still there. Rule 2 turned 574 stance times and 525 bounces of 0 into honest empty
values, so an average of stance time is now an average of real contacts. Temperature is flagged
empty in all 3,746 rows: the watch never recorded it.

### One chart

```python
import matplotlib.pyplot as plt

mins = run["elapsed_s"] / 60
miss = marked["stance_time_ms"].isna()
flag = marked["stance_time_ms_flag"] == "outside range"
fig, ax = plt.subplots(figsize=(9, 3.6))
ax.plot(mins[~miss & ~flag], marked.loc[~miss & ~flag, "stance_time_ms"], ".", ms=2, color="0.4", label="stance time")
ax.plot(mins[flag], marked.loc[flag, "stance_time_ms"], "x", ms=6, color="k", label="outside 100-400 ms (kept)")
ax.plot(mins[miss], np.full(miss.sum(), 40), "|", ms=8, color="k", label="missing (empty or 0)")
for end, g in pauses.items():
    ax.axvspan(mins[end] - g / 60, mins[end], color="0.85", lw=0)
ax.set(xlabel="minutes since the start (pauses shaded)", ylabel="stance time (ms)", ylim=(0, 500))
ax.legend(loc="upper left", fontsize=8)
plt.tight_layout()
print(f"missing stance times within 30 s after a pause: {int((miss & (run['elapsed_s'].sub(run['elapsed_s'].where(marked['gap_before_s'] > 0).ffill()) < 30)).sum())}")
```

Output:

```
missing stance times within 30 s after a pause: 160
```

![Stance time in milliseconds against minutes since the start, about 94 minutes. Dots mostly between about 200 and 300 ms; short vertical marks at the bottom where stance time is missing (empty or zero code), clustered at the start, around the shaded pauses and through minutes 40 to 70; crosses for kept out-of-range values, six single values just under 100 ms and a run of 17 near 470 ms at about minute 69.](https://apopt.com/course/tutorials/q12-missing-values/c05-1.png)

The marks are not scattered at random. They cluster at the start, around the pauses, and through
minutes 40 to 70, where short fast efforts alternate with walking: the watch stops estimating
contact time while the runner walks or stands and needs a few seconds to start again. That pattern
is information. Now look at the kept out-of-range values. The six just under 100 ms are single
seconds, four of them at walking speed: likely errors. The 17 seconds near 470 ms in a row, at
about 1.5 m/s, are a walk, and long contacts are normal when walking; the 100 to 400 ms rule was
written for running. A rule that deleted every row with a missing or odd stance time would have
removed the start of every effort and the walk between them.

**For the athlete:** "Contact time was measured for most of your running; the gaps are at the
start and around your stops, so your average contact time describes your running, not your stops."

## With your own data

Run the same cells on one of your own exported activities, with the rules from your own data
dictionary (Q-11). Look at where the missing values fall before you decide anything about them.

## References

- *Data-Driven Athletics*, Chapter 4, Cleaning (Section 4.3) and Keep the raw file: provenance and a change log (Section 4.3.1).

---
Text CC BY 4.0, code MIT. IRSRI Sports Research Institute.
