Lesson 5.1Module 5: Missing values45 minIntermediate
Handling missing values in music data
Find missing values, including the ones that don't look missing, then fill gaps in daily streams and in audio. Test each method against the truth and see how filling can fool your statistics.
Real data has holes. A streaming dashboard skips a day when a server fails, a chart only lists the top 100, an audio file drops a few milliseconds over a bad connection, and an analysis tool gives up on a track and writes 0. Every method in this course assumes the series is complete and evenly spaced, so missing values have to be dealt with first. This lesson shows how to find them, including the disguised ones, how to fill them, and how to check whether your filling helped or quietly made things worse.
Set up
You need data.csv from the Spotify dataset (lesson 2.1) and christmas_pageviews.csv (lesson 2.2).
import wave
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.stats.diagnostic import acorr_ljungbox
def save_wav(name, x, sr):
"""Save a numpy array as a 16-bit mono WAV file you can play (from lesson 1.2)."""
pcm = (np.clip(x, -1, 1) * 0.8 * 32767).astype(np.int16)
with wave.open(name, "wb") as f:
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(sr)
f.writeframes(pcm.tobytes())Why it's missing matters more than how much
Before filling anything, ask why a value is missing. Statisticians, following Donald Rubin (1976), distinguish three cases:
- Missing by pure chance. A server crash wipes a random day of streams. The missing days are like a random sample of all days, so leaving them out doesn't bias anything; it only loses information.
- Missing for a reason you can see. Stream counts are missing more often on weekends, because a reporting system only runs on weekdays. That's a problem if you ignore it (your averages lean towards weekdays), but because you know the reason, you can allow for it.
- Missing because of the value itself. A song disappears from the Billboard Hot 100 because it fell below number 100. The missing weeks are exactly the weeks when it was doing worst. Fill them by drawing a line between its last two chart positions and you invent a song that never fell off the chart. Average only the weeks it charted and you overstate its success. This kind of gap is the hardest, because the data can't tell you what you're missing.
No filling method can fix the third case on its own. You need knowledge from outside the data, such as "missing from the chart means below 100".
Finding missing values
Missing values come in three disguises.
1. Marked as missing
pandas marks a missing value as NaN ("not a number"). These are the easy ones: series.isna().sum() counts them, and most pandas functions skip them automatically. The Spotify file has none:
tracks = pd.read_csv("data.csv")
print("NaN values in the whole file:", tracks.isna().sum().sum())2. Disguised as a real value
That doesn't mean nothing is missing. Look at the lowest tempo in the file:
print("Lowest tempo:", tracks["tempo"].min(), "BPM")
zero = tracks[tracks["tempo"] == 0]
print(len(zero), "tracks have a tempo of exactly 0")
print(zero[["tempo", "speechiness", "danceability", "valence"]].describe().loc[["mean", "max"]].round(3))A tempo of 0 beats per minute is impossible. Those 143 tracks also have zero speechiness, danceability and valence: the audio analysis failed completely and wrote zeros instead of leaving a gap. Lesson 4.4 found the same problem in the dates, where 1 January stood in for "unknown day". Placeholders like 0, −1, 999, 1 January or "N/A" typed as text are the most dangerous kind of missing value, because every calculation treats them as real.
The fix is to turn them into honest NaNs:
tracks["tempo"] = tracks["tempo"].replace(0, np.nan)
print("Tempo values now marked missing:", tracks["tempo"].isna().sum())Here the damage was small: 143 tracks out of 170,000 barely move most yearly averages. But a handful of zeros in a small group can move its average a lot, and a placeholder never announces itself. Make a habit of checking each column's minimum and maximum, and asking whether they're possible.
3. Missing rows
In a time series, a missing value often isn't a NaN at all: the row is simply absent. Suppose a dashboard export skipped three days of the Christmas song's views:
views = pd.read_csv("christmas_pageviews.csv", index_col="date", parse_dates=True)["views"]
gappy = views.drop(pd.to_datetime(["2024-03-05", "2024-03-06", "2024-03-12"]))
print("Rows:", len(gappy), " NaN values:", gappy.isna().sum())
complete = gappy.asfreq("D") # one row per calendar day
print("Rows:", len(complete), " NaN values:", complete.isna().sum())gappy has no NaNs at all, so isna() reports nothing wrong. But calculations that work row by row, like .diff(), .shift() and .rolling(7), would silently treat 4 March and 7 March as neighbours. asfreq("D") puts every calendar day back, with NaN where data is missing. Always do this with time series before anything else, using "D" for daily, "W" for weekly or "MS" for monthly data.
Filling gaps: a fair test
We'll compare three ways to fill a gap in daily page views (on the log scale, as usual):
- Carry forward: repeat the last known value until the gap ends.
- Linear interpolation: draw a straight line from the value before the gap to the value after it.
- Same days last year: take the values from 52 weeks earlier (364 days, so the weekdays match), shifted up or down by how much this year differed from last year over the four weeks before the gap.
How can we tell which works best? The Christmas data is complete, so we can delete values on purpose, fill them, and compare with the truth. That's the only honest way to judge a filling method. We'll try three kinds of gap:
- 10% of days missing at random, scattered singly through the data,
- a two-week block at the December peak (10–23 December 2024),
- a two-week block in a quiet month (1–14 June 2025).
log_v = np.log(views)
def carry_forward(s):
return s.ffill()
def linear(s):
return s.interpolate()
def same_days_last_year(s):
out = s.copy()
last_year = log_v.shift(364)
gap_id = s.notna().cumsum()[s.isna()] # numbers each run of missing days
for _, days in gap_id.groupby(gap_id):
start = days.index[0]
before = s.loc[start - pd.Timedelta(days=28): start - pd.Timedelta(days=1)]
level_shift = (before - last_year.loc[before.index]).mean()
out.loc[days.index] = last_year.loc[days.index] + level_shift
return out
rng = np.random.default_rng(1)
scattered = pd.Series(False, index=log_v.index)
scattered.loc[rng.choice(log_v.loc["2017":].index, 330, replace=False)] = True
december = pd.Series(log_v.index.to_series().between("2024-12-10", "2024-12-23"), index=log_v.index)
june = pd.Series(log_v.index.to_series().between("2025-06-01", "2025-06-14"), index=log_v.index)
def error(filled, gaps):
"""Average error on the deleted days, as a % of the true views."""
true = np.exp(log_v[gaps])
return (np.abs(np.exp(filled[gaps]) - true) / true).mean() * 100
results = {}
for gap_name, gaps in [("Scattered days", scattered), ("December block", december), ("June block", june)]:
with_gaps = log_v.mask(gaps) # delete the chosen days
results[gap_name] = {f.__name__: error(f(with_gaps), gaps) for f in (carry_forward, linear, same_days_last_year)}
print(pd.DataFrame(results).round(1))The average errors, in % of the true views:
- Scattered single days: linear interpolation wins (about 9%). With a known value on each side, a straight line between them is hard to beat. Carry forward is a little worse (14%), and last year's values are worst (19%): day-to-day noise from a year ago is no guide to today.
- December block: the order reverses. Linear interpolation is now the worst (38%), and last year's December, rescaled, is best (21%). Linear interpolation heads steadily from the value before the gap to the much higher one after it (Christmas Eve), so it overshoots for most of the fortnight. In reality, views stayed fairly flat until the last few days and then shot up. Last year's December has that shape.
- June block: linear and carry forward tie at about 13%; last year is worst (22%). In a quiet month there's no shape to borrow, so last year's noise only adds error.
There's no single best method. The right fill depends on the length of the gap and on what the series is doing during it. Here's the December gap up close:
gaps = december
with_gaps = log_v.mask(gaps)
window = slice("2024-11-25", "2025-01-05")
fig, ax = plt.subplots(figsize=(10, 3.6))
ax.plot(views[window].index, views[window].values, color="grey", linewidth=2, label="What really happened")
for f, colour in [(carry_forward, "C3"), (linear, "C0"), (same_days_last_year, "C1")]:
filled = np.exp(f(with_gaps))[gaps]
ax.plot(filled.index, filled.values, linewidth=2, color=colour, label=f.__name__.replace("_", " "))
ax.axvspan(pd.Timestamp("2024-12-10"), pd.Timestamp("2024-12-23"), color="grey", alpha=0.12)
ax.set_ylabel("Views per day")
ax.set_title("Filling a two-week gap at the Christmas peak")
ax.legend(fontsize=8, loc="upper left")
plt.show()Filling can fool you
A filled value is a guess, but every later calculation treats it as data. That has consequences. Here's a series of pure white noise (lesson 4.2), with 30% of its values deleted at random and then filled by linear interpolation:
noise = pd.Series(rng.normal(size=1000))
holes = noise.mask(rng.random(1000) < 0.3)
filled = holes.interpolate()
for name, s in [("Original", noise), ("Interpolated", filled.dropna())]:
p = acorr_ljungbox(s, lags=[10])["lb_pvalue"].iloc[0]
print(f"{name:13s} lag-1 autocorrelation {s.autocorr(1):5.2f} spread {s.std():.2f} Ljung-Box p = {p:.1e}")The original passes the white-noise test easily. After filling, the lag-1 autocorrelation jumps from about 0 to 0.33, and the Ljung–Box test rejects white noise overwhelmingly. Every interpolated value is an average of its neighbours, so the filling created memory that wasn't in the data, and it also shrank the spread a little. A model fitted to the filled series would "find" a pattern that we put there ourselves.
So:
- Fill as little as you can. Many statistics (averages, correlations between columns) can simply skip missing values.
- Keep a record of which values were filled, for example in a column of
True/False, so you can check whether a result depends on them. - Report results with and without the filled values when they make up more than a small share of the data.
Dropouts in audio
Audio has missing values too. When a stream or a wireless connection drops a packet, a few milliseconds of samples are lost. Players can't stop and wait, so they fill the gap, a job called packet-loss concealment. It's the same problem as above, at 22,050 values a second.
Let's make a held note (a fundamental of 220.5 Hz plus a few harmonics, chosen so the wave repeats exactly every 100 samples), knock out 12 short gaps of 2 milliseconds and 4 longer ones of 30 milliseconds, and try two repairs:
- Linear interpolation across each gap, as before.
- Copy the previous cycle: fill each sample with the one exactly one wave-cycle (100 samples) earlier. This is the audio version of "same days last year": borrow the shape from the last repeat of the pattern.
sr = 22050
t = np.arange(3 * sr) / sr
f0 = sr / 100 # 220.5 Hz: one cycle is exactly 100 samples
note = sum(np.sin(2 * np.pi * k * f0 * t) / k for k in (1, 2, 3, 4)) / 2
note *= np.minimum(1, np.minimum(t / 0.05, (3 - t) / 0.3)) # gentle fade in and out
lost = np.zeros(len(note), dtype=bool)
starts = rng.choice(np.arange(sr // 4, len(note) - sr // 2), 16, replace=False)
for i, s in enumerate(starts):
lost[s : s + (44 if i < 12 else 661)] = True # 12 gaps of 2 ms, then 4 gaps of 30 ms
dropped = np.where(lost, 0.0, note) # what you'd hear with no repair: silence, with clicks
linear_fix = pd.Series(np.where(lost, np.nan, note)).interpolate().values
cycle_fix = dropped.copy()
for i in np.flatnonzero(lost):
cycle_fix[i] = cycle_fix[i - 100] # one cycle earlier (already repaired if it was lost too)
for name, x in [("original", note), ("dropouts", dropped), ("linear_fix", linear_fix), ("cycle_fix", cycle_fix)]:
save_wav(f"{name}.wav", x, sr)
rms = np.sqrt(np.mean((x[lost] - note[lost]) ** 2)) / np.sqrt(np.mean(note[lost] ** 2))
print(f"{name:11s} error in the lost samples: {rms:.0%} of the signal")Zoom in on one of the long gaps to see why:
long_gap = starts[12]
view = slice(long_gap - 150, long_gap + 811)
ms = (np.arange(len(note))[view] - long_gap) / sr * 1000
fig, ax = plt.subplots(figsize=(10, 3.4))
ax.plot(ms, note[view], color="grey", linewidth=3, alpha=0.6, label="Original")
ax.plot(ms, linear_fix[view], color="C0", linewidth=1.2, label="Linear interpolation")
ax.plot(ms, cycle_fix[view], color="C1", linewidth=1, linestyle="--", label="Copy previous cycle")
ax.axvspan(0, 661 / sr * 1000, color="grey", alpha=0.12)
ax.set_xlabel("Milliseconds from the start of the gap")
ax.set_title("A 30 ms dropout: a straight line versus the shape of the wave")
ax.set_ylim(-1, 1.25)
ax.legend(fontsize=8, loc="upper center", ncol=3)
plt.show()Across 2 milliseconds, the wave barely changes, so a straight line is a fair guess and your ear can't tell. Across 30 milliseconds the wave goes through more than six cycles, and a straight line simply erases them. Over all the lost samples, linear interpolation's error is 114% of the signal: worse, by this measure, than leaving silence (100%), because a straight line is on the wrong side of the wave about half the time. Copying the previous cycle keeps the shape, and its error here is 0%. That's a little too good to be true: our test note repeats exactly every 100 samples, while real music changes pitch and loudness, so real repairs are close but never perfect. It's the same lesson as the December gap: short gaps can be bridged; long gaps need the pattern. Real packet-loss concealment in phone calls and streaming works on this idea, with refinements for sounds that change over time.
Rules of thumb
- Ask why it's missing before anything else. If the gap depends on the value itself (a song off the chart), no filling method will rescue you without outside knowledge.
- Look for disguised missing values: impossible values (a tempo of 0), placeholders (1 January), and missing rows (use
asfreq). - Short gaps: linear interpolation is usually fine.
- Long gaps in a seasonal or repeating series: borrow the pattern, from last year, last week or the last cycle.
- Judge a method by deleting known values and comparing, not by how the filled series looks.
- Filling creates memory and shrinks variance. Mark filled values, and check that your conclusions survive without them.
Key ideas
- Missing by chance, for a visible reason, or because of the value itself (Rubin's three cases). The last is the most dangerous.
- The worst missing values are disguised: impossible values, placeholders and absent rows.
asfreqrestores missing rows in a time series, sodiff,shiftandrollingwork correctly.- No method is best everywhere. Linear interpolation wins for scattered single days and loses badly across the December peak.
- Test filling methods by deleting values you know and measuring the error.
- Interpolation adds autocorrelation: filled white noise fails the white-noise test.
- In audio, packet-loss concealment fills dropouts by copying the last cycle of the wave, the same idea as borrowing last year's season.
Try it yourself
- Find other columns in
data.csvwith impossible or suspicious values. (Hint: check the minimum loudness, and the tracks whoseduration_msis under 30 seconds.) - Repeat the filling experiment with a two-week gap in April 2024, which contains the April 2024 spike from lesson 2.2. Which method is best now, and what happens to the spike?
- In the white-noise example, delete 10% instead of 30%. How much memory does interpolation create now?
- In the audio example, try copying from 101 samples earlier instead of 100. What do you hear, and why?
Next lesson: Autocorrelation: finding the beat
The course
Music as Data: Time Series with Python
1Music as a time series
2Seeing patterns
3Decomposition and stationarity
4Testing a time series
5Missing values
6Autocorrelation and forecasting
7Smoothing and Granger causality
8From time series to AI music