Lesson 1.3Module 1: Music as a time series35 minBeginner
Loading music data into pandas: audio, MIDI and streaming numbers
Open three real file types, a stereo WAV, a MIDI file and a CSV of streaming numbers, and turn each into a pandas time series you can plot, check and resample.
So far we've made our own data. Real work starts with files: a recording from a session, a MIDI file from your music software, a spreadsheet of streams exported from a dashboard. This lesson opens one of each and turns it into a pandas time series. Each format stores time differently, and the hardest part of loading music data is getting the time right.
The files
Download the three practice files and put them in the folder you run Python from:
- chords_stereo.wav: six seconds of audio, CD quality, in stereo. Four chords (C, G, A minor, F) on the left channel, and a bass line on the right.
- twinkle.mid: the first two lines of "Twinkle, Twinkle, Little Star" (a traditional tune), with a melody and a bass part.
- streams.csv: simulated daily streams for two made-up tracks over 90 days. A few days are missing on purpose, as they often are in real exports.
You'll need one more library for MIDI files, mido:
pip install midoimport wave
import mido
import numpy as np
import pandas as pd
import matplotlib.pyplot as pltAudio: reading a WAV file
A WAV file has a short header describing the audio, followed by the samples. Python's built-in wave module reads both:
with wave.open("chords_stereo.wav", "rb") as f:
sr = f.getframerate() # samples per second, per channel
channels = f.getnchannels() # 1 = mono, 2 = stereo
width = f.getsampwidth() # bytes per sample: 2 = 16-bit
n = f.getnframes() # number of samples per channel
raw = f.readframes(n) # the samples themselves, as raw bytes
print(f"{sr:,} Hz, {channels} channels, {8 * width}-bit, {n:,} frames = {n / sr:.1f} seconds")Always read the header before the samples. It tells you the three things you need to turn bytes into a time series: how many channels, how many bytes per sample, and the sample rate, which is what converts sample numbers into seconds.
In a stereo file the samples are interleaved: left, right, left, right. numpy can read the bytes as 16-bit integers and fold them into two columns:
samples = np.frombuffer(raw, dtype=np.int16).reshape(-1, channels) / 32768 # scale to -1 … +1
audio = pd.DataFrame(samples, columns=["left", "right"],
index=pd.to_timedelta(np.arange(n) / sr, unit="s"))
audio.index.name = "time"
print(audio.head())
print(audio.abs().max())Dividing by 32,768 rescales the 16-bit integers (which run from −32,768 to 32,767) to the range −1 to +1, the usual convention for audio. The index turns each row number into a time, just as in lesson 1.1. Now the file is a two-column time series:
loud = (audio ** 2).resample("50ms").mean() ** 0.5 # RMS loudness of each channel, every 50 ms
fig, ax = plt.subplots(2, 1, figsize=(10, 4.4), sharex=True)
step = 20 # plot every 20th sample: plenty for the eye
secs = audio.index.total_seconds()
ax[0].plot(secs[::step], audio["left"].values[::step], linewidth=0.4, label="Left: chords")
ax[0].plot(secs[::step], audio["right"].values[::step], linewidth=0.4, alpha=0.8, label="Right: bass")
ax[0].set_title("chords_stereo.wav: both channels")
ax[0].legend(loc="upper right", fontsize=8)
ax[1].plot(loud.index.total_seconds(), loud["left"], label="Left")
ax[1].plot(loud.index.total_seconds(), loud["right"], label="Right")
ax[1].set_title("Loudness every 50 ms: four chords, each struck and fading")
ax[1].legend(loc="upper right", fontsize=8)
ax[1].set_xlabel("Time (seconds)")
plt.tight_layout()
plt.show()Four chords, one every 1.5 seconds, each struck and then fading. The resample step is the same one you used in lesson 1.1. Once audio is in a time-indexed DataFrame, everything pandas can do with time works on it.
Other audio formats. Thewavemodule reads uncompressed WAV files only. For MP3, FLAC or OGG, installsoundfileorlibrosa(for examplelibrosa.load("song.mp3", sr=None)). They hand you the same thing: a numpy array of samples and a sample rate, and from there everything in this lesson applies.
A CSV of streams
Last, the business data. CSV files are the most common way to get numbers out of a dashboard, and pandas reads them with one line. The parse_dates option tells it that the date column holds dates, not text:
streams = pd.read_csv("streams.csv", parse_dates=["date"])
print(streams.head())
print(streams.dtypes)
print(streams["track"].value_counts())The file is in long format: one row per track per day, as most exports are. For time-series work you usually want wide format: one column per track, one row per date. pivot does it:
wide = streams.pivot(index="date", columns="track", values="streams")
print(wide.shape)Two tracks for 90 days should mean 90 rows, but there are only 89. A whole day is missing from the file, and pandas has no way of knowing. asfreq("D") tells it the data should be daily, which brings the missing days back as gaps (NaN, "not a number"):
wide = wide.asfreq("D")
print(wide.shape)
print(wide.isna().sum())
print(wide[wide.isna().any(axis=1)])Now you can see the full picture: one day missing for both tracks, and two more missing for "Slow Burn" only. Always check for gaps when you load a time series. Many methods quietly assume the rows are evenly spaced, and a missing day would shift everything after it. Module 5 covers what to do about gaps; for now, just find them.
ax = wide.plot(figsize=(10, 3.4), linewidth=1.2, marker=".", markersize=3)
ax.set_ylabel("Streams per day")
ax.set_xlabel("")
ax.set_title("streams.csv (simulated): a fading launch and a slow climber, with gaps")
plt.show()The gaps show as breaks in the lines. The two tracks also tell different stories: a launch that fades, and a song that grows by word of mouth. In lesson 1.4 we'll look at data like this across many tracks at once, which economists call panel data.
Key ideas
- Audio files store samples plus a header. Read the header first: the channel count, the sample width and the sample rate are what turn bytes into a time series.
- Stereo samples are interleaved: reshape them into one column per channel.
- MIDI files store instructions, not sound. Times are gaps between messages, in ticks; mido converts them to seconds. A table of notes needs note starts matched with note stops, and a
note_onwith velocity 0 counts as a stop. - Converting events to a regular series (counting notes per beat, for example) is a modelling choice.
- CSVs: use
parse_dates, pivot long data to wide, thenasfreqto reveal missing dates. Always check for gaps.
Try it yourself
- Resample the WAV's loudness every 1.5 seconds (
"1500ms") instead of every 50 ms. How many values do you get, and why does each one line up with a chord? - Change the note count to
resample("250ms"). What do the zeros now tell you about the rhythm? - Load a MIDI file of your own (any song exported from your music software) and draw its piano roll. Which instruments use which channels?
- Find the date of the highest-streaming day for each track with
wide.idxmax(). Then compare each track's weekly average in its first and last full week, usingwide.resample("W").mean().
Next lesson: Panel data: many songs, measured over time. Follow twelve songs at once, line them up by release day, and measure how fast each one fades.
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