# Q-11: Write a data dictionary for one file

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

Web page: https://apopt.com/course/tutorials/q11-data-dictionary/ · Data: https://apopt.com/data/tutorials/q11-data-dictionary/

## The decision

A runner wants contact time and cadence from a season of watch files. Before any average, write
down what each column means, in which unit, what values are possible, and how the file says "no value".

## 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), as converted from the watch's FIT file with GPS positions removed The instructor's own run on 11 May 2026, from the course case file `athletes/jh/watch/records/`, published under his name.

### A file does not say what it means

A **data dictionary** is a table with one row per field of a file: its name, its meaning, its
unit, its type, its allowed range and its **missing-value code**, the way the file writes "no
value" (Section 4.2.5). The file here is one of the instructor's real runs, the 11 May 2026
afternoon run from the course case file: one row per second the watch recorded, 12 columns, GPS
positions removed. Open it and list what is there.

*Predict first:* The run lasted about 94 minutes from start to finish. Will the file have about 5,640 rows, or fewer?

```python
import pandas as pd

run = pd.read_csv("raw/2026-05-11_1507_running.csv", dtype=str)    # as text first: see what is written
print(run.shape)
print(run.iloc[[0, 1, 1000]].to_string(index=False))
print("empty cells per column:", run.isna().sum().to_dict())
```

Output:

```
(3746, 12)
                time elapsed_s distance_m speed_mps heart_rate_bpm cadence_spm altitude_m power_w stance_time_ms vertical_oscillation_mm step_length_mm temperature_c
2026-05-11T21:07:12Z       0.0        0.0       NaN            NaN         NaN        NaN     NaN            NaN                     NaN            NaN           NaN
2026-05-11T21:07:13Z       1.0        0.0       NaN             87         NaN        NaN     NaN            NaN                     NaN            NaN           NaN
2026-05-11T21:38:17Z    1865.0     3014.5     3.358            127         174     1408.0     249          205.0                   101.0         1160.0           NaN
empty cells per column: {'time': 0, 'elapsed_s': 0, 'distance_m': 0, 'speed_mps': 37, 'heart_rate_bpm': 1, 'cadence_spm': 39, 'altitude_m': 101, 'power_w': 39, 'stance_time_ms': 37, 'vertical_oscillation_mm': 37, 'step_length_mm': 37, 'temperature_c': 3746}
```

3,746 rows for a run whose last `elapsed_s` is 5,640: the watch writes no rows while it is
paused. The `temperature_c` column is empty in every row. Now write the dictionary **before**
checking the values against it. The meanings and units come from the case file's own
description; the allowed ranges are your rules, set from what a runner can do, not from this file.

```python
FIELDS = [  # field, meaning, unit, type, low, high, missing code
    ("time", "time of the sample", "ISO 8601, UTC", "time", None, None, "never"),
    ("elapsed_s", "seconds since the start, pauses included", "s", "decimal", 0, 36000, "never"),
    ("distance_m", "distance since the start", "m", "decimal", 0, 100000, "never"),
    ("speed_mps", "speed from the watch", "m/s", "decimal", 0, 12, "empty"),
    ("heart_rate_bpm", "optical heart rate at the wrist", "beats/min", "integer", 30, 220, "empty"),
    ("cadence_spm", "steps a minute, both feet", "steps/min", "decimal", 0, 240, "empty"),
    ("altitude_m", "barometric altitude", "m", "decimal", -500, 5000, "empty"),
    ("power_w", "running power estimated by the watch", "W", "integer", 0, 1500, "empty"),
    ("stance_time_ms", "ground contact time", "ms", "integer", 100, 400, "empty or 0"),
    ("vertical_oscillation_mm", "vertical bounce of the torso", "mm", "integer", 30, 150, "empty or 0"),
    ("step_length_mm", "step length", "mm", "integer", 0, 2500, "empty"),
    ("temperature_c", "watch temperature sensor", "deg C", "decimal", -30, 60, "empty"),
]
dictionary = pd.DataFrame(FIELDS, columns=["field", "meaning", "unit", "type", "low", "high", "missing"])
import os
os.makedirs("clean", exist_ok=True)
dictionary.to_csv("clean/data_dictionary.csv", index=False)
print(dictionary[["field", "unit", "low", "high", "missing"]].to_string(index=False))
```

Output:

```
                  field          unit    low     high    missing
                   time ISO 8601, UTC    NaN      NaN      never
              elapsed_s             s    0.0  36000.0      never
             distance_m             m    0.0 100000.0      never
              speed_mps           m/s    0.0     12.0      empty
         heart_rate_bpm     beats/min   30.0    220.0      empty
            cadence_spm     steps/min    0.0    240.0      empty
             altitude_m             m -500.0   5000.0      empty
                power_w             W    0.0   1500.0      empty
         stance_time_ms            ms  100.0    400.0 empty or 0
vertical_oscillation_mm            mm   30.0    150.0 empty or 0
         step_length_mm            mm    0.0   2500.0      empty
          temperature_c         deg C  -30.0     60.0      empty
```

Two rows carry most of the value. Cadence here counts **both** feet (a watch's own file often
counts one, Section 4.2.5), so the range is up to 240. And a stance time of 0 ms is not a
contact; the case file notes that the watch writes 0 when it did not estimate one, so 0 is a
second missing-value code for stance time and vertical bounce.

### Check the file against it

*Predict first:* Which field will have the most values outside its range?

```python
rows = []
for f in dictionary.itertuples():
    if pd.isna(f.low):                          # no range to check (the time stamps)
        continue
    empty = run[f.field].isna()
    x = pd.to_numeric(run[f.field], errors="coerce")
    zero_code = (x == 0) if "0" in f.missing else pd.Series(False, index=x.index)
    outside = ((x < f.low) | (x > f.high)) & ~zero_code
    rows.append({"field": f.field, "empty": int(empty.sum()), "not a number": int((x.isna() & ~empty).sum()),
                 "0 = no estimate": int(zero_code.sum()), "outside range": int(outside.sum())})
check = pd.DataFrame(rows).set_index("field")
print(check.to_string())
st, sp = run["stance_time_ms"].astype(float), run["speed_mps"].astype(float)
print(f"stance time 0 while slower than 2 m/s (walking or stopped): {int(((st == 0) & (sp < 2)).sum())} of {int((st == 0).sum())}")
print(f"stance times outside 100-400 ms: shortest {st[st > 0].min():.0f}, longest {st.max():.0f}")
```

Output:

```
                         empty  not a number  0 = no estimate  outside range
field                                                                       
elapsed_s                    0             0                0              0
distance_m                   0             0                0              0
speed_mps                   37             0                0              0
heart_rate_bpm               1             0                0              0
cadence_spm                 39             0                0              0
altitude_m                 101             0                0              0
power_w                     39             0                0              0
stance_time_ms              37             0              574             24
vertical_oscillation_mm     37             0              525              1
step_length_mm              37             0                0              0
temperature_c             3746             0                0              0
stance time 0 while slower than 2 m/s (walking or stopped): 492 of 574
stance times outside 100-400 ms: shortest 82, longest 474
```

### One chart

```python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(7, 4))
left = pd.Series(0, index=check.index)
for col, hatch, shade in [("empty", "", "0.3"), ("0 = no estimate", "//", "0.6"), ("outside range", "xx", "0.9")]:
    ax.barh(check.index, check[col], left=left, color=shade, hatch=hatch, edgecolor="k", label=col)
    left = left + check[col]
ax.set(xlabel="rows (of 3,746)", xlim=(0, 3746))
ax.legend(loc="lower right")
plt.tight_layout()
```

![Horizontal bars, one row per field, of the number of rows that are empty, use the zero code, or fall outside the allowed range. Temperature is empty in all 3,746 rows; stance time and vertical bounce have several hundred zero-code rows; altitude has about 100 empty rows; the other fields have few.](https://apopt.com/course/tutorials/q11-data-dictionary/c07-1.png)

The file passes most of its rules, and the failures are informative. Temperature was never
recorded. Stance time and vertical bounce use 0 for "no estimate" in several hundred rows,
mostly while walking or stopped, which an average would otherwise count as real contacts of zero
length. The few values outside range, 24 stance times and one vertical bounce, are for Q-12 to
mark, not to delete. Update the dictionary with what you found:
the zero code is now written down for the next person.

**For the athlete:** "Your watch file is in good shape for pace, heart rate and cadence; contact
time is missing for about one second in six, so we'll report it only from the seconds where the
watch measured it."

## With your own data

Export one activity from your own watch or phone app as CSV (or convert a FIT file with the
fitdecode library, Q-16), write its dictionary before you look at the values, and run the check.
Remove any position columns before you share the file.

## References

- *Data-Driven Athletics*, Chapter 4, The data dictionary (Section 4.2.5) and Cleaning (Section 4.3).

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