Foundations to Frontier
Tests
C. Programming, Tools and HPC › C1 Python for Science

pandas and Polars: Tabular Data

Most engineering data is tabular: telemetry streams, test logs, experiment results. pandas gives labelled, typed columns (DataFrame/Series) with indexing, missing-data handling, time series (resample, rolling), split–apply–combine (groupby), joins (merge) and reshaping (pivot, melt). Polars is a newer, Rust-based DataFrame library with a lazy query engine and multi-threading. This topic covers the core operations and idioms, the performance rules (vectorize, avoid row-wise apply, use categoricals) and when to reach for Polars. In the exercises you clean and analyse spacecraft telemetry (resampling, interpolation, joins, limit checks, rolling anomaly detection) and measure the costs of apply, itertuples, groupby and string columns.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A spreadsheet you can program

A DataFrame is a table: named columns (time, subsystem, voltage) and rows (one measurement each). Unlike a spreadsheet, you work on it with short commands such as “average voltage per subsystem per minute” or “rows where temperature exceeded its limit”, and the same command works on 100 rows or 100 million. pandas is the classic Python library for this; Polars is a newer, faster one with similar ideas.

groupby: split, apply, combine
group by: aggregate:
show stage:
timesubsystemmodevalue
00:00ADCSnominal11.8
00:01ADCSslew14.6
00:02ADCSslew15.3
00:02COMMSdownlink5.2
00:03COMMSdownlink5.6
00:00EPSnominal28.1
00:01EPSnominal27.9
00:03EPSdownlink27.2
ADCS: mean([11.8, 14.6, 15.3]) = 13.90
COMMS: mean([5.2, 5.6]) = 5.40
EPS: mean([28.1, 27.9, 27.2]) = 27.73
subsystemvalue
ADCS13.90
COMMS5.40
EPS27.73
# pandas
df.groupby("subsystem")["value"].mean()

# Polars (lazy, multi-threaded)
df.group_by("subsystem").agg(pl.col("value").mean()).sort("subsystem")
Nearly every data question ("average power per subsystem", "peak load per mode", "samples per hour") is split–apply–combine. pandas runs each aggregation in compiled code per group; Polars plans the whole query first (lazy) and runs it across all cores, often several times faster on large tables. Either way, express the question as one grouped operation instead of a Python loop over rows.
Why engineers care

Housekeeping telemetry, thermal-vacuum test logs, wind-tunnel runs, flight-test data and ML experiment results all arrive as tables. Fast, correct grouping, joining and time-resampling is what turns gigabytes of raw logs into the plot that answers “did the battery heater cycle as designed?”.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A DataFrame is…
  2. 2. 'Average voltage per subsystem' is a…
  3. 3. Polars is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.

Core objects and selection

import pandas as pd
df = pd.read_csv("telemetry.csv", parse_dates=["time"])
df.head(); df.dtypes; df.describe()
df["value"]                          # a Series
df.loc[df["subsystem"] == "EPS", ["time", "value"]]    # label-based with a boolean mask
df.iloc[0:5, 1]                      # position-based
df.query("value > 15 and subsystem == 'ADCS'")
df.assign(power=df.volts * df.amps)  # new column, vectorized

Missing data

NaN marks missing values: df.isna().mean() gives the fraction missing per column, dropna(), fillna(v), ffill(), and interpolate() (linear, or method="time" on a time index).

Time series

With a DatetimeIndex: resample("1min").mean() bins in time, rolling(6).median() gives moving windows, shift(1) lags (to avoid peeking at the current sample), and tz_localize/tz_convert handle time zones (UTC for spacecraft!).

📝 Quick check (Level 1)
0/3 answered
  1. 1. df.loc selects by…
  2. 2. resample('1min').mean() requires…
  3. 3. df.isna().mean() returns…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.

Split–apply–combine and joins

df.groupby("subsystem")["value"].agg(["count", "mean", "std", "max"])
df.groupby(["subsystem", pd.Grouper(key="time", freq="1h")])["value"].mean()
df.groupby("subsystem")["value"].transform(lambda s: s - s.mean())   # same shape as df
df.merge(meta, on="subsystem", how="left")     # SQL-style joins: inner, left, right, outer

Reshaping

pivot / pivot_table go from long (time, sensor, value) to wide (one column per sensor), and melt goes back. Wide tables suit plotting and matrix maths; long tables suit grouping.

Polars in one paragraph

Polars has column-oriented Arrow memory, expressions (pl.col("value").mean()) and a lazy API: pl.scan_csv(...).filter(...).group_by(...).agg(...).collect() builds a query plan, optimizes it (predicate and projection pushdown) and executes it on all cores. There is no index and no chained-assignment ambiguity. It is often 5–30× faster than pandas on large data. (Polars isn’t available in this in-browser Python, so the exercises use pandas, and the concepts transfer directly.)

🐍 Exercise 1: analyse spacecraft telemetry
From long-format telemetry (time, subsystem, value) with dropouts and a fault: build a per-minute wide table (pivot + resample), a per-subsystem summary joined with unit/limit metadata, fill gaps by interpolation within each subsystem, find limit violations with a join and a mask, and flag anomalies with a rolling median/std detector that only looks at past samples.
📝 Quick check (Level 2)
0/3 answered
  1. 1. groupby(...).transform(f) returns…
  2. 2. A left merge keeps…
  3. 3. Polars' lazy API lets the engine…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Why apply is slow

df.apply(f, axis=1) builds a Series object per row and calls a Python function: thousands of interpreter operations per row. Column arithmetic runs one compiled loop over contiguous arrays. Prefer vectorized expressions, np.where/np.select for conditionals, groupby for per-group logic, and map with a dict for lookups.

Memory

Object columns store a pointer per row to a Python string (about 50+ bytes each). The category dtype stores small integer codes plus a list of unique labels, ideal for low-cardinality text like subsystem names or modes. Also check df.memory_usage(deep=True), downcast floats (float32) where precision allows, and use Arrow-backed dtypes (dtype_backend="pyarrow").

Correctness traps

  • Chained assignment: df[df.x > 0]["y"] = 1 may modify a copy. Use df.loc[mask, "y"] = 1 (pandas 3 makes copy-on-write the default).
  • Look-ahead bias: a centred rolling window or an un-shifted statistic uses the current or future sample. Shift by one for detectors.
  • Time zones and duplicate timestamps when merging telemetry from different ground stations.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Best dtype for a 'mode' column with 5 distinct strings and 10⁷ rows:
  2. 2. df.loc[mask, 'y'] = 1 is preferred over df[mask]['y'] = 1 because…
  3. 3. Shifting the rolling statistic by one sample prevents…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

pandas, measured

Exercise 1 (2 h of 10 s telemetry from 3 subsystems, 45 dropouts, a 2-minute ADCS fault). Interpolation fills all gaps. The limit join flags exactly the 12 fault samples (01:06:40–01:08:30). The causal rolling detector flags 7 samples: the fault onset at 01:06:40 plus a few false alarms, the usual price of a 4σ threshold on 2160 samples.

Exercise 2 (20 000 rows, CPython):

operation time relative
df.volts * df.amps (vectorized) 0.015 ms 1×
list comprehension over itertuples() 4.5 ms ≈ 300×
df.apply(..., axis=1) 31 ms ≈ 2100×
groupby mean 0.38 ms —
hand-written dict loop 1.45 ms ≈ 4× groupby

The groupby advantage is modest here because 20 000 rows is small and the loop is simple. It widens with size and aggregation complexity. The 5-label subsystem column takes 1.07 MB as object strings and 20.6 kB as category: 52× smaller. In the browser (Pyodide, 32-bit) the timings are slower and the object column is smaller, 0.59 MB vs 20.3 kB (29×): memory and timing figures differ by platform, but the ranking is the same.

🐍 Exercise 2 (research): what does pandas code really cost?
On a 20 000-row frame, time vectorized column arithmetic vs itertuples vs apply(axis=1) (checking results agree), groupby vs a Python dict loop, and compare the memory of a string column stored as object vs category.

In AI, robotics and aerospace

  • Telemetry and test-data analysis: resample, join with limit databases, detect anomalies.
  • Experiment tracking: collect ML runs’ metrics in DataFrames, group by hyperparameters.
  • Polars / DuckDB for multi-gigabyte logs that overwhelm pandas.
  • Parquet (columnar, compressed, typed) as the storage format for both.

References

  1. W. McKinney (2022). Python for Data Analysis, 3rd ed. O’Reilly.
  2. pandas documentation: Group by: split-apply-combine, Time series, Copy-on-Write (pandas.pydata.org).
  3. H. Wickham (2011). “The split-apply-combine strategy for data analysis.” Journal of Statistical Software, 40(1).
  4. Polars documentation, User guide: lazy API (docs.pola.rs).
  5. Apache Arrow project. Columnar format specification (arrow.apache.org).