Module 22 · Lesson 22 of 64

Grouping, missing data and time series

Summarize raw boot and latency captures into grouped tables, handle NaN gaps, and downsample them over a datetime index with pandas.

  • Beginner to advanced
  • 9 min read
  • 40 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM; Python 3 with pandas installed (pip install pandas); no board is required for this lesson

Your place in the module
By the end you can 4 objectives
  • Group parsed measurements by key columns and produce sorted summary tables with groupby and agg
  • Detect NaN gaps with isna and choose between dropna and fillna for capture data
  • Build a DatetimeIndex and downsample or smooth captures with resample and rolling
  • Attach and convert timezones on timestamps with stdlib zoneinfo
Video coming soonGrouping, missing data and time series
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from NumPy and pandas fundamentals
  • An ndarray stores one fixed dtype in a contiguous buffer, so arithmetic runs as compiled C loops instead of Python loops.
  • Basic slicing of an ndarray returns a view that shares memory; fancy indexing and boolean masks return copies.
  • pandas loc slices include the end label; iloc slices exclude the end position, like Python lists.
01

Grouping raw measurements into summary tables

3 min read

In the previous lesson you built DataFrames from parsed rows. This lesson groups those measurements, handles NaN gaps and resamples them over a datetime index so raw captures become summary tables.

A boot-time study leaves you with many rows: one per boot, each with a timestamp, a board name and a duration in seconds. systemd-analyze prints the kernel and userspace boot time for a single boot; recording it across many reboots builds the raw table you want to summarize. Reading rows one by one tells you nothing; you want one line per board with its mean, best and worst boot time. That is what does, and turns each group into a single summary row.

python
import pandas as pd

boots = pd.read_csv("boots.csv")          # columns: timestamp, board, seconds
summary = (
    boots.groupby("board")["seconds"]
    .agg(["mean", "min", "max", "count"])
    .sort_values("mean", ascending=False)
)
print(summary)

groupby("board")["seconds"] selects the seconds column grouped by board. .agg(["mean", "min", "max", "count"]) computes all four reductions per board. The result is a DataFrame indexed by board name with one row per distinct board, and sort_values("mean", ascending=False) puts the slowest board first, which is what you want when you are hunting a boot regression.

Named aggregations give clearer column names and let every column use its own function:

python
summary = boots.groupby("board").agg(
    mean_s=("seconds", "mean"),
    best_s=("seconds", "min"),
    worst_s=("seconds", "max"),
    boots=("seconds", "count"),
).sort_values("mean_s", ascending=False)

The keyword mean_s= names the output column, and ("seconds", "mean") says "apply mean to the seconds column". This is the form to prefer once a summary has more than two columns, because the list form produces a two-level column index that is awkward to reference later.

Two details matter for real captures. You can group by several keys at once with groupby(["board", "config"]), which produces one row per combination. And groupby drops rows whose grouping key is NaN by default, so a row with a missing board name silently disappears from the summary: the gaps in the next section are not only about numbers.

groupby, agg and sortRaw rowsmanycapturerowsgroupbyboardsplit bykeyagg meanmin maxsummarytableone row perboardsort bymeanslowestfirstRaw rowsmanycapturerowsgroupbyboardsplit bykeyagg meanmin maxsummarytableone row perboardsort bymeanslowestfirst
How groupby splits rows, agg reduces each group, and sort_values orders the summary.
02

Missing data: NaN, gaps, and why captures lose rows

3 min read

Raw captures have gaps, and those gaps arrive in the DataFrame as . NaN is not None and not the string "nan": it is a genuine float value, which has two consequences that trip people up. First, arithmetic with NaN returns NaN, so nan + 1.0 is still nan. Second, NaN compares unequal to itself, so value == float("nan") is always False and cannot be used to find missing values.

Use instead:

python
import pandas as pd

df = pd.read_csv("latency.csv")
print(df.isna().sum())        # NaN count per column

df.isna() returns a DataFrame of booleans the same shape as df, and .sum() adds the True values per column, so the output is one number per column telling you how many gaps it has. The companion notna() is the inverse.

Where do the gaps come from? They are a property of real hardware and networks, not a bug in the parser:

  • An I2C read can fail with a NACK or a bus error, so that sample is simply never recorded.
  • A serial capture drops a line when the host reads slower than the board writes and the kernel buffer overflows.
  • A ping to a board that is rebooting times out, leaving a timestamp with no round-trip value.
  • A boot log line is absent because a service failed before it printed its "started" message.

Once you know the gaps exist, you decide what to do with them. deletes the affected rows, and patches them:

python
df.dropna()                                # remove any row with a NaN
df.dropna(subset=["latency_ms"])           # remove rows missing this column only
df.dropna(how="all")                       # remove rows that are entirely NaN

df["latency_ms"].fillna(df["latency_ms"].median())   # replace with the median
df["latency_ms"].ffill()                              # carry the last valid value forward
df["latency_ms"].bfill()                              # carry the next valid value backward

ffill (forward fill) and bfill (backward fill) respect row order, which is why they belong to the time-series work in the next section: on a sorted index, ffill means "assume the value stayed the same as the last reading".

One subtlety decides many mistakes: pandas reductions such as mean, sum, min and max skip NaN by default. df["latency_ms"].mean() returns a number even when some values are missing, and so does groupby(...).mean(). NaN returns only where there is nothing to reduce: a group whose values are all NaN has a mean of NaN, and a resample bucket with no sample at all is NaN. Do not confuse "reductions skip NaN" with "NaN never shows up in results".

Do not fill latency gaps with zero

A missing latency reading means "we have no value", not "the round trip took zero time". fillna(0) drags the mean down and makes a slow link look faster than it is. For latency use ffill() (the value probably changed little) or dropna(). Zero-fill is defensible only when a missing value genuinely means zero, such as a counter that did not increment.

dropna, fillna and ffilldropna()fillna(value)ffill()What it doesremoves rowswith NaNreplaces NaNwith aconstantcarries lastvalue forwardRow countshrinksunchangedunchangedBest forindependentrowsmissing meansa known valueordered timeseries
dropna, fillna and ffill differ in whether they remove rows or replace values.
03

Time series: a datetime index, resample and rolling

5 min read

Every row in a boot or latency capture carries a timestamp, so the natural index is time. To use pandas' time machinery you parse the timestamp column and make it the index:

python
lat = pd.read_csv("latency.csv")           # columns: timestamp, board, latency_ms
lat["timestamp"] = pd.to_datetime(lat["timestamp"])
lat = lat.set_index("timestamp").sort_index()

is what set_index produces here. pd.to_datetime parses the strings, and sort_index() orders rows by time. Keep the sort: a time-window rolling requires a monotonic index and raises ValueError: index values must be monotonic on out-of-order rows, and ffill/bfill assume row order is time order. (resample itself tolerates unsorted input, but sort first anyway.)

downsamples a high-rate capture to a regular grid:

python
per_second = lat.resample("1s")["latency_ms"].mean()

A 100 ms sampling loop writes ten rows per second; resample("1s").mean() collapses them into one value per second. The output grid is fixed: there is a row for every second, and a second in which no sample landed becomes NaN, which is exactly the gap from the previous section reappearing at the grid level. You then choose ffill() or dropna() on the resampled result.

is a different tool. It does not change the grid; it returns one value per input row, each the mean of the trailing window:

python
smoothed = lat["latency_ms"].rolling("5s").mean()

Each output value is the mean of the samples in the five seconds ending at that row. The result has the same number of rows as the input and the same timestamps, but the point-to-point jitter is smoothed away so a slow trend becomes visible despite the noise.

For boot data the pattern is the same. Each row is one boot's total seconds with a timestamp, and resample("1D") gives the mean boot time per day, while rolling(10) (ten boots, not ten seconds) shows whether a recent change made boots slower. For latency data, resample to one second to shrink the file before plotting, and rolling to see the trend.

Going deeperExplore the mechanism

Resample rules, date ranges and downsampling. The string passed to resample is an offset alias: a number plus a unit. Use the lowercase forms "s" seconds, "min" minutes, "h" hours, "D" days, "ms" milliseconds, "us" microseconds and "ns" nanoseconds (the older "S", "H", "L", "U" and "N" spellings are deprecated in pandas 2.2 and later). So "100ms", "1min", "1h" and "1D" are all valid, and "10min" buckets a long capture into ten-minute blocks.

pd.date_range builds a regular DatetimeIndex, which is how you generate synthetic captures to test resample and rolling without hardware:

python
idx = pd.date_range("2026-12-01 09:00:00", periods=600, freq="100ms")
sig = pd.Series(range(len(idx)), index=idx)

Downsampling a high-rate capture is a choice of aggregation, not just mean. resample("1s").max() keeps the worst latency in each second, which is the right summary when you care about jitter spikes. resample("1s").last() keeps the last sample, useful when you want a snapshot rather than an average. Upsampling the other way, to a grid finer than the data (for example "100ms" on data sampled every second), inserts NaN between real samples; follow it with ffill() or interpolate().

Going deeperExplore the mechanism

Timezones: zoneinfo, not pytz. A Timestamp and a DatetimeIndex are either naive (no timezone) or aware (a timezone attached). tz_localize attaches a zone to naive times, and tz_convert moves aware times to another zone:

python
idx = (
    pd.to_datetime(["2026-12-01 09:00:00"])
    .tz_localize("UTC")
    .tz_convert("Africa/Cairo")
)

Prefer the standard library since Python 3.9: from zoneinfo import ZoneInfo; pd.Timestamp("2026-12-01 09:00", tz=ZoneInfo("Africa/Cairo")). zoneinfo reads the system tz database, the same one the C library's tzset(3) uses. The third-party pytz package does the same job but is legacy; new code should use zoneinfo.

Boards almost always log in UTC. If you read a board's UTC log and a host log in your local zone, localize or convert both to one common zone before you merge, sort or resample them. Pandas raises when some operations mix naive and aware timestamps, and comparisons between aware timestamps in different zones silently convert, so leaving the zones unstated invites a one-hour-off result that is hard to notice.

resample versus rollingresample('1s')rolling('1s')Output rowsone persecondone per inputrowGridfixedcalendarfollows dataUsedownsample,alignsmooth jitter
resample buckets samples onto a fixed grid; rolling slides a window and keeps one value per sample.

Summaries and smoothed series are only useful when a human can see them. The next lesson, matplotlib and choosing the right chart, turns the grouped tables and resampled series from this lesson into plots, and answers which chart fits boot times versus latency distributions.

Key takeaways

  • groupby splits rows into groups, agg reduces each group to one summary row, and sort_values orders the summary
  • NaN is a float sentinel that poisons arithmetic and is never equal to itself, so gaps are found with isna and repaired with dropna, fillna or ffill
  • A sorted DatetimeIndex enables resample, which buckets samples onto a fixed grid, and rolling, which slides a window without changing the grid
  • Timezone-aware timestamps are attached with tz_localize and moved with tz_convert, and stdlib zoneinfo is preferred over the legacy pytz package
Reflect
  1. Explain to a colleague, in two sentences: group parsed measurements by key columns and produce sorted summary tables with groupby and agg
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close