← Data detective

The same job in pandas

Do the last two lessons again with pandas: read the CSV into a table, then take an average, a maximum and a filtered table in one line each.

The last lesson took a loop to find an average. A data scientist writes it in one line.

You have counted, totalled and filtered by hand with loops. pandas is the tool people use for exactly those jobs. It reads a CSV into a table (a DataFrame), keeps numbers as numbers, and gives each job a name: .mean() for the average, .max() for the biggest, len(...) for how many rows.

import pandas as pd loads it, and pd.read_csv("music.csv") reads the file. Copy those two lines for now: you will use them every time.

How this lesson works: Predict, Run, Investigate, Modify, Make
PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

lesson.py
import pandas as pd

songs = pd.read_csv("music.csv")

print(round(songs["minutes"].mean(), 1))

songs["minutes"] is one column of the table. What does .mean() do to it?

The file has 49 songs. What does the last line print?

RunRun it and compare the result with your prediction.

Run

Run it (pandas takes a few seconds to load the first time) and read the output next to the loops you wrote last lesson.

Line What it does The loop it replaces
pd.read_csv("music.csv") Reads the file into a table open, csv.DictReader and list
songs["minutes"].mean() Average of a column Adding in a loop, then dividing
songs["minutes"].max() Biggest in a column Keeping the longest so far
songs[songs["genre"] == "pop"] Only the rows where the test is true A loop with an if
lesson.py
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"] == "pop"]
print(len(pop), "pop songs, average", round(pop["minutes"].mean(), 1), "minutes")
Try it yourselfYour edits are saved in this browser.

InvestigateTrace how each line of code connects to what you see.

Investigate

lesson.py
import pandas as pd

songs = pd.read_csv("music.csv")

rock = songs[songs["genre"] == "rock"]
print(len(rock))
print(rock["title"])

len(table) is the number of rows.

Inside out: the test first, then the keep.

Run the code. How many rock songs are there?

What does `songs[songs["genre"] == "rock"]` give?

ModifyChange the code on purpose and check the result.

Modify

Change the program so the last line is about rock songs instead of pop.

Try it yourselfYour edits are saved in this browser.
Build up to it
Which line gives the average length of the rock songs, if rock holds only the rock rows?

Need a hint?

Before a hint: what kind of stuck is this? Try a strategy first

Change the word in the test, and the name the output uses.

Another hint

Use "rock" in place of "pop".

Show the number of rock songs and their average length.

    Run your program. This ticks when your code does all of the above.

    MakeBuild something new using what you have learned. Expect a few tries; that is normal.

    Make

    Find out how many songs are from before 1990, and how long the longest of them is.

    Try it yourselfYour edits are saved in this browser.
    Need a hint?

    Before a hint: what kind of stuck is this? Try a strategy first

    Filter the table with a test on the year column, then use len and .max().

    Another hint

    old = songs[songs["year"] < 1990]

    Print how many songs are from before 1990 and the length of the longest one.

      Run your program. This ticks when your code does all of the above.

      Now you can
      Next lesson4. A bar chart in textCount every genre at once with a dictionary, then draw each count as a bar of
      For teachers

      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. About 30 minutes.

      Open the teacher guide: answers, solutions, slides and a worksheet.

      Students will be able to

      Running the lesson

      1. Predict: the error option catches students who remember float(). pandas reads numbers as numbers.
      2. Run: put last lesson's loop beside each pandas line. The point is that pandas is the same job with a name.
      3. Investigate: read the filter from the inside out. The test makes True and False for every row.
      4. Make: the test uses a number, so no quotes round 1990.

      The hard part (on purpose)

      Reading a filter in one line. Say it aloud: the songs where the genre is pop.

      When students get stuck

      Stretch and support

      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.

      Where it leads

      Next lessons: a chart and cleaning by hand, then the dashboard, where pandas sits behind an app.

      What each step is for