Lesson 1.4Module 1: Music as a time series35 minBeginner
Panel data: many songs, measured over time
Track twelve songs at once. Learn the shape of panel data, why songs released on different days need lining up by 'days since release', and how to measure how fast each song fades.
One song's streams make a time series. A whole release schedule, a label's catalogue or a playlist's tracks make a panel: many units, each measured over time. Panels let you ask questions one series can't answer: do songs usually fade this fast? Is this launch unusual? In this lesson you'll build a panel of twelve songs, look at it from three angles, and measure how quickly each one fades.
What panel data is
Panel data (also called longitudinal data) follows the same set of units over time. Economists use it to follow people, firms or countries year after year. In music the units are often songs, artists or playlists, and the time steps are days or weeks.
A panel has two dimensions, so you can slice it two ways:
- One unit over time is a time series: one song's daily streams.
- All units at one time is a cross-section: every song's streams on 1 March.
A panel where every unit is observed at every time is balanced. Music panels almost never are, because songs come out on different days. That turns out to be the most important thing to handle correctly.
Build a panel
Real streaming data for many songs isn't freely shareable, so we'll simulate a release schedule whose ingredients we know. That has a big advantage: at the end we can check whether our measurements recover the truth.
Each of our twelve songs is released on a Friday (most new music comes out on Fridays), starts at its own launch size, and fades at its own rate. We describe the fade by a half-life: the number of days until daily streams fall to half.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rng = np.random.default_rng(2026)
n = 12
songs = pd.DataFrame({
"track": [f"Track {chr(65 + i)}" for i in range(n)], # Track A, Track B, ...
"release": pd.Timestamp("2026-01-02") + pd.to_timedelta(7 * rng.integers(0, 17, n), unit="D"),
"launch": rng.lognormal(mean=10, sigma=0.8, size=n).round(), # day-one streams
"half_life": rng.uniform(7, 45, n).round(1), # days to fall by half
})
print(songs)Now give each song a daily series from its release day to the end of June:
end = pd.Timestamp("2026-06-30")
rows = []
for s in songs.itertuples():
dates = pd.date_range(s.release, end, freq="D")
day = np.arange(len(dates)) # days since release
streams = s.launch * 0.5 ** (day / s.half_life) * rng.normal(1, 0.05, len(dates))
rows.append(pd.DataFrame({"track": s.track, "date": dates, "day": day,
"streams": streams.round().astype(int)}))
long = pd.concat(rows, ignore_index=True)
print(long.head())
print(long.shape)
print(long.groupby("track").size())This is the long format from lesson 1.3: one row per song per day. The counts per track differ because the songs came out on different dates, so the panel is unbalanced.
Three views of a panel
pandas handles panels well with a two-level index, song first and date second:
panel = long.set_index(["track", "date"]).sort_index()
one_song = panel.loc["Track A", "streams"] # view 1: one song over time
one_day = panel.xs("2026-03-01", level="date")["streams"] # view 2: every song on one day
print(one_song.head())
print(one_day.sort_values(ascending=False))The cross-section for 1 March lists only the seven songs that were out by then. The third view is the whole panel in wide format, one column per song, which is the easiest to plot:
wide = long.pivot(index="date", columns="track", values="streams")
ax = wide.plot(figsize=(10, 3.6), linewidth=1, legend=False, logy=True)
ax.set_ylabel("Streams per day (log scale)")
ax.set_xlabel("")
ax.set_title("Twelve simulated songs in calendar time")
plt.show()Two things to notice. The y-axis is on a log scale, where each step up multiplies by ten. Our songs launch at 13,000 to 39,000 streams a day and fade to a handful, so on a normal scale every song's tail would be squashed flat against the bottom. On a log scale, steady decay at a fixed half-life is a straight line, which makes fades easy to compare by eye.
The other thing: the empty space before each song starts. In the wide table those cells are NaN, just like the missing days in lesson 1.3, but they mean something completely different:
print(wide.isna().sum().sort_values())A song that hasn't been released has no streams by definition. That's not missing data, and it must never be filled in. Lesson 1.3's gaps were real days with lost numbers. Before you treat a gap in a panel, ask which kind it is.
Line the songs up: days since release
Calendar time is the wrong clock for comparing launches. Track A's first week was in January, Track L's in April. To ask "how do songs usually behave after release?" we need event time: days since each song's own release. We already stored it in the day column, so we pivot on that instead:
by_day = long.pivot(index="day", columns="track", values="streams")
ax = by_day.plot(figsize=(10, 3.6), linewidth=1, alpha=0.6, legend=False, logy=True)
by_day.median(axis=1).plot(ax=ax, color="C2", linewidth=3, label="Median song")
ax.set_xlabel("Days since release")
ax.set_ylabel("Streams per day (log scale)")
ax.set_title("The same songs in event time: every launch starts at day 0")
ax.legend(handles=[ax.lines[-1]], loc="upper right", fontsize=8) # label only the median line
plt.show()Now every song starts at day 0, and the differences between them are clear: some songs fall away within weeks, others hold on. The panel is unbalanced in event time too. Songs released early have longer tails, so the right-hand side of the chart has fewer songs in it, and the median there is based on fewer of them. Keep that in mind before reading too much into the far right of any event-time chart.
Measure how fast each song fades
Here's where the log scale pays off. If streams halve every h days, the log of streams falls in a straight line:
log(streams) = log(launch) − (ln 2 / h) × day
So fitting a straight line to log(streams) against day, separately for each song, gives each song's decay rate, and from that its half-life. One catch: the log of zero is undefined (it's minus infinity), and Track F fades so fast that by summer it's down to 0 streams on some days. So the function drops zero days before fitting. Whenever you take logs of counts, check for zeros first. groupby runs the same calculation on every song:
def half_life(g):
g = g[g["streams"] > 0] # log(0) is undefined: skip zero days
slope, intercept = np.polyfit(g["day"], np.log(g["streams"]), 1) # straight-line fit
return np.log(2) / -slope
estimated = long.groupby("track")[["day", "streams"]].apply(half_life).round(1)
check = songs.set_index("track")[["half_life"]].assign(estimated=estimated)
print(check)Because we simulated the data, we can check the estimates against the half-lives we built in:
plt.figure(figsize=(5.5, 5))
plt.scatter(check["half_life"], check["estimated"], s=40, color="C1", zorder=3)
plt.plot([0, 50], [0, 50], ":", color="C3", label="Perfect estimate")
for name, r in check.iterrows():
plt.annotate(name.replace("Track ", ""), (r["half_life"], r["estimated"]), xytext=(5, -10),
textcoords="offset points", fontsize=8)
plt.xlabel("True half-life (days)")
plt.ylabel("Estimated half-life (days)")
plt.title("Recovering each song's fade from its data")
plt.legend(loc="upper left", fontsize=8)
plt.show()The points sit almost exactly on the diagonal: the line fits recover every song's half-life. Real data is never this tidy. Real songs get playlisted, go viral or appear in an advert, and their fades aren't straight lines. But the method is the same one analysts use, and testing a method on simulated data where you know the answer, before trusting it on real data, is one of the most useful habits in data analysis.
The economist's view. We fitted a separate line for each song. Panel econometrics goes further: a fixed-effects model gives every song its own level (some songs are simply bigger) but estimates shared effects, such as a common decay rate or the lift from being added to a playlist, from all the songs at once. Separating "this song is big" from "this event made it bigger" is exactly what panels are for, and later modules build up to it.
Key ideas
- Panel data follows many units (songs, artists, playlists) over time. Slice it by unit to get a time series, or by date to get a cross-section.
- Music panels are usually unbalanced: songs start on different days.
- In pandas, keep panels long with a
(track, date)index, and pivot to wide when you want to plot or compare. - A gap before release is structurally empty, not missing data. Never fill it in.
- Compare launches in event time (days since release), not calendar time, and watch out for the thin, ragged tail.
- On a log scale, steady decay is a straight line, so a straight-line fit to log(streams) estimates each song's half-life.
Try it yourself
- Which song had the most streams on 1 April? Use
panel.xs("2026-04-01", level="date"). - Change the noise from 5% to 30% (
rng.normal(1, 0.3, ...)) and re-run the half-life check. How far do the points move from the diagonal? Do short-lived or long-lived songs suffer more? - Use
by_day.count(axis=1)to plot how many songs contribute at each day since release. After how many days does the median rest on fewer than half the songs? - Add a "catalogue floor" to the simulation, so streams never fall below 10% of launch:
streams = s.launch * (0.9 * 0.5 ** (day / s.half_life) + 0.1) * .... Does a straight-line fit on the log scale still recover the half-life? Why not?
Next: Module 2 starts with real data: Has music got louder? Visualising 100 years of Spotify data.
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
- 5.1Handling missing values in music data coming soon
6Autocorrelation and forecasting
- 6.1Autocorrelation: finding the beat coming soon
- 6.2Partial autocorrelation and lag plots coming soon
- 6.3How forecastable is a hit? coming soon
7Smoothing and Granger causality
- 7.1Smoothing: moving averages and loudness envelopes coming soon
- 7.2Granger causality: does social-media buzz predict streams? coming soon
8From time series to AI music
- 8.1From forecasting to generating: how AI music models predict what comes next coming soon