Students redo the CSV jobs with pandas: read_csv into a table, .mean() and .max() on a column, len for rows, and a test inside square brackets to filter.
Open these in Waypoints Prepare with one click. To share a file another way, copy its address and paste it into Load URL, or download the file and import it. In Prepare, the worksheet's Teacher edition shows the answers; the student copy hides them.
Predict and Run 10 min · Investigate 8 min · Modify and Make 12 min
On the slides at these points. Students can do the whole lesson on their own; these are for the room. In the deck, the Run, Modify and Make slides have the live playground in them (the tutorial link is the backup), and the notes above are in each slide's speaker notes.
Show one pandas line. Pairs write the loop it replaces, then swap and check each other's.
Reading a filter in one line. Say it aloud: the songs where the genre is pop.
| What you will see | A question to ask | The fix |
|---|---|---|
| KeyError: 'minute' | What is the column called in the file? | Column names must match the first line of the CSV exactly, and the same capitals. |
| A table printed instead of a number. | Did you pick a column before .mean()? | songs["minutes"].mean() picks the column first. |
| The filter test uses a single =. | Is this a test or an assignment? | A test needs ==. A single = stores a value. |
One possible solution for each task. Other correct programs are fine.
import pandas as pd
songs = pd.read_csv("music.csv")
print(songs.head())
print(len(songs), "songs")
print("Average length:", round(songs["minutes"].mean(), 1), "minutes")
print("Longest:", songs["minutes"].max(), "minutes")
pop = songs[songs["genre"] == "rock"]
print(len(pop), "pop songs, average", round(pop["minutes"].mean(), 1), "minutes")
import pandas as pd
songs = pd.read_csv("music.csv")
old = songs[songs["year"] < 1990]
print(len(old), "songs before 1990")
print("Longest:", old["minutes"].max(), "minutes")
Stretch: Print the average length of every genre with songs.groupby("genre")["minutes"].mean().
Support: Give the whole program with the genre blank for students to fill in.
What does songs[songs["year"] < 1990] do?
It keeps only the rows where the year is below 1990, and gives them back as a smaller table.
Next lessons: a chart and cleaning by hand, then the dashboard, where pandas sits behind an app.