Lesson 7 · Data Science with DEB
A smooth NDVI line can hide a long period without usable observations. Before interpreting a seasonal curve, check which dates contain measurements, how far apart they are and whether any plotted values were estimated.
In lesson six, we checked where a raster places its values. Now we check when measurements exist. This free article uses six deliberately constructed dates, not real satellite observations. No video accompanies it.
Six dates, four observations
Page contents
Imagine that each row represents one scheduled observation of the same area. Two dates have no usable value. A missing value is different from an observed NDVI of zero: zero is a possible numerical measurement and must remain valid when its quality checks pass. See the masking lesson for the spatial version of this distinction.
| Date (2026) | Synthetic NDVI | Status |
|---|---|---|
| 1 June | 0.20 | Observed |
| 6 June | 0.30 | Observed |
| 11 June | Missing | No observation |
| 26 June | Missing | No observation |
| 1 July | 0.65 | Observed |
| 6 July | 0.50 | Observed |
The arithmetic mean of the four observed values is (0.20 + 0.30 + 0.65 + 0.50) / 4 = 0.4125. Incorrectly substituting two zeros changes the denominator to six and gives 0.2750. That drop is introduced by data handling; it is not observed vegetation change.
Show the gap on a calendar axis

Open the figure at full size to inspect the labels on a phone.
The horizontal axis uses actual elapsed calendar time. There are 25 days between the valid measurements on 6 June and 1 July. Equally spacing the six rows would conceal their unequal timing. Dropping missing rows and joining the remaining points would also draw an uninterrupted line across that interval. In the plotting script, missing values remain NaN so the line breaks.
Interpolation creates an estimate
Linear interpolation assumes a straight path between two valid endpoints. It does not recover a measurement that was never observed. Here the example permits interpolation only when the bracketing valid observations are at most ten days apart. Both missing dates lie inside a 25-day bracket, so they stay missing. The ten-day limit is an arbitrary teaching rule, not a recommended satellite, crop or operational threshold.
A real rule needs a stated purpose, temporal dynamics and evidence appropriate to the use. A smooth estimated curve must be labelled separately from observations. Avoid extrapolating beyond the first or last valid measurement unless you have an explicit model and evidence for doing so.
Run the reproducible example
Save the first script as time_series_gaps.py in a writable folder. It uses only Python’s standard library and writes synthetic_observations.csv and verification.json beside itself. Running it again overwrites those generated outputs. The script is a transparent teaching example for these fixed, sorted dates, not a general production time-series processor.
python time_series_gaps.py
"""Synthetic teaching experiment: gaps are not zero observations.
No satellite inputs, crop labels, or interpolation accuracy claims.
Run with Python 3.10+; standard library only.
"""
from datetime import date
from pathlib import Path
import csv
import json
import math
ROOT = Path(__file__).resolve().parent
rows = [
("2026-06-01", 0.20),
("2026-06-06", 0.30),
("2026-06-11", None),
("2026-06-26", None),
("2026-07-01", 0.65),
("2026-07-06", 0.50),
]
valid = [(date.fromisoformat(d), v) for d, v in rows if v is not None]
observed_mean = sum(v for _, v in valid) / len(valid)
wrong_zero_mean = sum(v or 0 for _, v in rows) / len(rows)
gaps = [(b[0] - a[0]).days for a, b in zip(valid, valid[1:])]
assert math.isclose(observed_mean, 0.4125)
assert math.isclose(wrong_zero_mean, 0.275)
assert max(gaps) == 25
# Ten days is an arbitrary teaching rule, not a crop-specific recommendation.
max_bracket_days = 10
output = []
for day_text, value in rows:
day = date.fromisoformat(day_text)
estimate = None
status = "observed" if value is not None else "missing"
if value is None:
left = [r for r in valid if r[0] < day]
right = [r for r in valid if r[0] > day]
if left and right:
a, b = left[-1], right[0]
width = (b[0] - a[0]).days
if width <= max_bracket_days:
estimate = a[1] + (b[1] - a[1]) * (day - a[0]).days / width
status = "modelled_linear"
else:
status = "missing_long_gap"
output.append((day_text, value, estimate, status))
assert all(r[2] is None for r in output)
assert sum(r[3] == "missing_long_gap" for r in output) == 2
with (ROOT / "synthetic_observations.csv").open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["date", "observed_ndvi", "modelled_ndvi", "status"])
writer.writerows(output)
result = {
"synthetic": True,
"scheduled_rows": len(rows),
"valid_observations": len(valid),
"observed_sample_mean": observed_mean,
"incorrect_zero_filled_sample_mean": wrong_zero_mean,
"largest_valid_observation_gap_days": max(gaps),
"illustrative_max_interpolation_bracket_days": max_bracket_days,
"long_gap_rows_left_missing": 2,
"limitation": "Sample means are not time-weighted seasonal means. No real crop or satellite validation.",
}
(ROOT / "verification.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
print(json.dumps(result, indent=2))
Expected checks: six scheduled rows, four valid observations, mean approximately 0.4125, incorrect zero-filled mean approximately 0.275, largest valid-observation gap 25 days, and two long-gap rows left missing. The assertions passed with Python 3.14. Floating-point output may display 0.27499999999999997 instead of 0.275.
Recreate the figure
Save this second script as plot_time_series.py in the same folder. Run the first script before it. The plot was generated with Matplotlib 3.11.0 and reviewed at 360 pixels wide; a crowded annotation was moved before publication. The script writes PNG, SVG and a narrow review copy. Matplotlib’s dependencies include Pillow, used for that review copy.
python -m pip install matplotlib==3.11.0
python plot_time_series.py
"""Plot synthetic observations using real date spacing; no long-gap bridge."""
from datetime import date
from pathlib import Path
import csv
import math
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
root = Path(__file__).resolve().parent
with (root / "synthetic_observations.csv").open(encoding="utf-8") as f:
records = list(csv.DictReader(f))
dates = [date.fromisoformat(r["date"]) for r in records]
observed = [float(r["observed_ndvi"]) if r["observed_ndvi"] else math.nan for r in records]
wrong = [v if math.isfinite(v) else 0.0 for v in observed]
plt.rcParams.update({"font.size": 15, "axes.titlesize": 18, "axes.labelsize": 15})
fig, axes = plt.subplots(2, 1, figsize=(7.2, 9.2), sharex=True, sharey=True, layout="constrained")
for ax in axes:
ax.set_ylim(-0.08, 0.9)
ax.set_yticks([0, 0.3, 0.6, 0.9])
ax.grid(axis="y", alpha=0.25)
ax.set_ylabel("Synthetic NDVI")
ax.spines[["top", "right"]].set_visible(False)
axes[0].plot(dates, observed, "o-", color="#126B5E", linewidth=2.5, markersize=9)
axes[0].axvspan(dates[1], dates[4], color="#D89417", alpha=0.10)
axes[0].annotate("25 days between\nvalid observations", xy=(mdates.date2num(dates[1]) + 12.5, 0.46), ha="center", fontsize=15)
axes[0].scatter([dates[2], dates[3]], [-0.035, -0.035], marker="x", color="#555555", s=70)
axes[0].text(0.02, 0.96, "4 observed samples; mean = 0.4125", transform=axes[0].transAxes, va="top", fontsize=14)
axes[0].set_title("A. Keep missing dates missing", loc="left", pad=12)
axes[1].plot(dates, wrong, "o--", color="#A6382F", linewidth=2, markersize=8)
axes[1].scatter([dates[2], dates[3]], [0, 0], marker="X", color="#A6382F", s=120, zorder=5)
axes[1].text(0.02, 0.96, "6 values after zero-fill; mean = 0.2750", transform=axes[1].transAxes, va="top", fontsize=14)
axes[1].set_title("B. Incorrectly replace missing with zero", loc="left", pad=12)
axes[1].set_xticks([dates[i] for i in [0, 2, 3, 5]])
axes[1].xaxis.set_major_formatter(mdates.DateFormatter("%d %b"))
axes[1].set_xlabel("2026 calendar dates (unequal spacing)")
fig.suptitle("Missing is not zero", fontsize=22, fontweight="bold")
fig.savefig(root / "time_series_gaps.png", dpi=200)
fig.savefig(root / "time_series_gaps.svg")
# Narrow-size QA artifact, not a separate data transformation.
from PIL import Image
with Image.open(root / "time_series_gaps.png") as im:
im.resize((360, round(im.height * 360 / im.width)), Image.Resampling.LANCZOS).save(root / "time_series_gaps_360.png")
print("Figure saved; Matplotlib", matplotlib.__version__)
What the mean cannot establish
The value 0.4125 is an observed-sample mean. It is not automatically a time-weighted seasonal mean. Each available sample contributes equally even though calendar intervals differ. Integrating a curve through the gap would introduce assumptions about unobserved conditions; it would not remove the uncertainty.
Four valid rows out of six describes this constructed schedule, not continuous coverage of two-thirds of the season. Missingness can be selective: for example, quality masking can remove some conditions more often than others. The available samples alone cannot establish that the unobserved period behaved similarly.
Before using real satellite time series
- Use a consistent area or explicitly track changes in footprint and usable area.
- Check dates, ordering and duplicates; preserve the distinction between acquisition dates and composite periods.
- Keep scale, units, preprocessing, grid alignment and quality masks consistent or document justified differences.
- Report valid observation counts, calendar gaps and usable-area fractions alongside summaries.
- Keep observations and modelled values in separate fields, with the modelling rule and its limits.
- Use independent evidence before interpreting a gap or an estimated curve as planting delay, crop stress or yield change.
Check your understanding
Does a missing date mean NDVI was zero? No. Missing means no usable value is available; a valid observed zero is a separate case.
Why is the largest gap 25 days? The calculation compares successive valid dates: 6 June to 1 July, even though two scheduled rows occur inside that interval.
Does a smooth interpolated curve prove what happened? No. It displays estimates under assumptions. In this example the long gap remains unfilled.
Sources and reuse
Plotting references: Matplotlib’s missing-value line example and date tick locators and formatters, reviewed 28 November 2026. The first explains why retaining masked/NaN positions breaks a line whereas removing them joins the remaining points. The second documents calendar-axis formatting.
All dates and NDVI values here are synthetic. No satellite retrieval, crop identification, biological validation or interpolation accuracy assessment was performed. The original example code and figure are available under the MIT License, copyright 2026 Data Science with DEB.
Return to the learning path. Next we will examine why changing valid area can change a field-level mean even when the underlying measurements do not change.