An optional extension after pandas: students make a numpy array from a list, multiply or average it in one line, and use a test inside square brackets to keep some numbers.
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 8 min · Investigate 7 min · Modify and Make 10 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 numpy line. Pairs write the loop it replaces, then swap and check each other's.
Reading a filter in one line. Say it aloud: the lengths where the length is over 4.
| What you will see | A question to ask | The fix |
|---|---|---|
| NameError: name 'np' is not defined | Did you import numpy first? | The first line is import numpy as np. |
| The mean looks like a very long decimal. | Did you round it? | round(short.mean(), 1) gives one decimal place. |
| Nothing is filtered, or all numbers print. | Is the test inside the square brackets? | lengths[lengths < 4] keeps rows; lengths < 4 alone only gives True and False. |
One possible solution for each task. Other correct programs are fine.
import numpy as np
lengths = np.array([3.5, 4.2, 2.8, 5.1, 3.9, 4.4])
print("Average:", round(lengths.mean(), 2), "minutes")
print("Average:", round((lengths * 60).mean()), "seconds")
print("Longest:", lengths.max(), "minutes")
import numpy as np
lengths = np.array([3.5, 4.2, 2.8, 5.1, 3.9, 4.4])
short = lengths[lengths < 4]
print(len(short), "songs under 4 minutes")
print("Average:", round(short.mean(), 1), "minutes")
Stretch: Print the lengths in seconds as whole numbers with np.round(lengths * 60).
Support: Give the whole program with the 4 blank for students to fill in.
What does lengths[lengths < 4] do?
It keeps only the numbers that are less than 4, and gives them back as a smaller array.
Pandas uses numpy underneath, so the same square-bracket test you used on a table works on an array too.