DATA SCIENCE · CYCLE 2 · L19b · TEXTBOOK CHAPTER
Same Numbers, New Tool
Clicking works for 18 rows. Code is a written recipe: it reruns on new data in one click, reads every row however many there are, and leaves every step on the page for anyone to check.
After this chapter, you can
- Say why a data scientist writes code instead of clicking.
- Read each line of a cell in plain English.
- Name each line’s twin in Sheets.
- Predict what a cell prints.
For your project: Python checks the numbers on your ANALYSIS tab. The checkpoint is at the end.
Why It Matters
In the autumn of 2020, Public Health England counted every positive COVID test in England each day. Each positive test started a clock: contact tracers aim to reach that person’s contacts within 48 hours.
The test results were loaded into an old Excel file type, XLS, that holds about 65,000 rows. Rows past the limit were left off. 15,841 positive tests were missing from the counts over 8 days, 25 September to 2 October 2020. A count of the rows going in and coming out would have shown the gap.
One line of code, len(df), prints how many rows were read. A recipe that counts what it read would have caught it on day one.
The Idea
Code is a written recipe
Code is a list of instructions a computer follows exactly, in order. You have written code already: =AVERAGE(B2:B33) is one instruction to Sheets. Python is a language for writing instructions, the one many data scientists use. pandas is a toolbox added onto Python for tables, like the functions Sheets has. Colab is a Google page where Python runs in your browser, one cell at a time.
Each line of pandas has a twin in Sheets. Nothing in L19b computed anything new: it got Thursday’s numbers a second way.
| In Sheets | In pandas | Said in English |
| Nothing to do: Sheets’ functions are always loaded | import pandas as pd | Get the pandas toolbox and call it pd. |
| File > Import the CSV | df = pd.read_csv(name) | Open the file as a table called df. |
| A tab of rows and columns | df | The table. |
| Count the rows | len(df) | How many rows. |
| Column B | df["Strong hand (cm)"] | The strong-hand column. |
| Fixing "12 cm" and blanks by hand | pd.to_numeric(..., errors="coerce") | Keep the numbers; anything else becomes blank. |
=AVERAGE | .mean() | The mean. |
=MEDIAN | .median() | The median. |
=STDEV | .std() | The standard deviation, dividing by n − 1. |
Six Rules for Reading a Line
The same six rules as your Colab page. Each one has an example, and what it does.
| The rule | An example, and what it does |
| 1 | Read top to bottom, one line at a time. | import pandas as pd Line 1 of a cell. It makes pd, so every line below it can use pd. |
| 2 | = means “call it”: the name on the left, what it is on the right. | five = pd.Series([12, 15, 15, 18, 20]) Makes a column of five numbers and calls it five. It shows nothing. |
| 3 | A name is a label someone made up. Programmers call it a variable. | hands = pd.Series([12, 15, 15, 18, 20]) The same five numbers, called hands this time. |
| 4 | The dot reaches inside something. A tool that belongs to a thing is a method. | five.mean() Asks five for its mean. |
| 5 | ( ) holds what you hand over. Quotes hold text, exactly as typed. | round(3.14159, 2) Hands round two arguments, 3.14159 and 2. It gives back 3.14. "12 cm" is a string, text, and no number. |
| 6 | print( ) shows it under the cell. | print(five.mean()) Shows 16.0 under the cell: the mean of five, written as a decimal. |
Worked Examples
Run it here
The cells in these three examples run real Python, on this page: press ▶ Run under a cell. Say your guess first, then run it. Run them in order, as in a notebook: Example 2’s cells make df, strong and other, and Example 3 uses them. The first run loads Python into your browser, which takes a moment.
Example 1 · Read a cell with the rules. Cell 1 of the L19b notebook.
1import pandas as pd
2five = pd.Series([12, 15, 15, 18, 20])
3print(round(five.std(), 2))
In Sheets this is: the =STDEV you used on Thursday, here on the five numbers 12, 15, 15, 18, 20.
In English:
- Get the pandas toolbox and call it pd.
- Make a column of the five numbers, and call it five.
- Print the standard deviation, dividing by n − 1, rounded to 2 places.
Predict: Thursday you worked these five by hand. What will it print?
Create a strategyRead line 3 inside out: the innermost ( ) first, then outward. Rule 4, then rule 5, then rule 6.
Apply the ideafive.std() asks five for its SD (rule 4). round(…, 2) rounds it to 2 places (rule 5). print( ) shows it (rule 6). Lines 1 and 2 show nothing: they only make pd and five.
Can’t run it here? Show what it prints
3.08
Reflect and check3.08 is the SD you built on Thursday one column at a time, and the number =STDEV gave in C10. Same numbers, new tool.
Example 2 · Count what you read. Cells 2 and 3 open the class catches file and count it.
1from google.colab import files
2import pandas as pd
3name = next(iter(files.upload()))
4df = pd.read_csv(name)
5print(len(df), "rows")
In Sheets this is: File > Import the CSV, then count the rows.
In English:
- Get the tool that opens files.
- Get the pandas toolbox and call it pd.
- Show a Choose files button, and call the name of the file you pick name.
- Open the file as a table called df.
- Print how many rows.
Predict: one row for each student. How many rows will it say?
Can’t run it here? Show what it prints
18 rows
Its twin in your Sheet: =COUNT(B2:B33) in G1 shows 18.
1strong = pd.to_numeric(df["Strong hand (cm)"], errors="coerce")
2other = pd.to_numeric(df["Other hand (cm)"], errors="coerce")
3print("Strong hand values used:", strong.count())
4print("Other hand values used:", other.count())
In Sheets this is: fixing "12 cm" and blanks by hand, then counting what is left.
In English:
- Keep only the numbers in the strong-hand column (anything else becomes blank), and call the result strong.
- Keep only the numbers in the other-hand column (anything else becomes blank), and call the result other.
- Print how many numbers the strong hand has.
- Print how many numbers the other hand has.
Predict: someone may have typed "12 cm" or left a box empty. How many numbers will each hand have?
Can’t run it here? Show what it prints
Strong hand values used: 18
Other hand values used: 18
Reflect and checkEvery catch in the class file was a clean number, so each hand kept all 18. Had one box said "12 cm", the strong hand would print 17: the "12 cm" becomes blank (NaN), and .count() skips it. Count twice, once for rows and once for numbers, and nothing goes missing without you knowing.
Example 3 · Same file, same numbers. Cell 4 finds each hand’s mean, median and SD. Then Cell 5 changes one word.
1print("Strong hand: mean", round(strong.mean(), 2), " median", strong.median(), " SD", round(strong.std(), 2))
2print("Other hand: mean", round(other.mean(), 2), " median", other.median(), " SD", round(other.std(), 2))
In Sheets this is: =AVERAGE, =MEDIAN and =STDEV on each hand’s column.
In English:
- Print the strong hand’s mean, median, and standard deviation dividing by n − 1.
- Print the other hand’s mean, median, and standard deviation dividing by n − 1.
Predict: which hand will have the bigger mean? Which will have the bigger SD?
Can’t run it here? Show what it prints
Strong hand: mean 14.72 median 14.5 SD 2.35
Other hand: mean 17.67 median 18.0 SD 5.97
The same as your Sheet from Thursday: E1 and F1 (the means), E2 and F2 (the SDs), E3 and F3 (the medians).
In Sheets this is: =STDEV on the strong-hand column.
In English:
- Print the strong hand’s standard deviation, dividing by n − 1, rounded to 2 places.
Predict: run it as it is: it prints 2.35, the SD from Cell 4. Now click in the cell and change .std() to .max(). The line asks for the strong hand’s largest catch instead. Say what it will print, then run it.
Can’t run it here? Show what it prints
19
Its twin, =MAX(B2:B33) in E4, shows 19.
Reflect and checkpandas keeps every mean and median as a decimal, so the other hand’s median prints 18.0. 18 and 18.0 are the same number. .max() prints 19 with no .0, because every catch in the file is a whole number. Sheets shows more places, like 14.72222222: round it to 2 and it is the same.
Now Type Your Own
Reading a cell is the first step. Next, change one, then write one. The Python practice page has short tasks that check themselves, the class file, and a notebook of your own.
In your project
Your project’s LOG tab says how many rows you have, counted: =COUNT in Sheets, or len(df) in pandas. A count like that would have caught Public Health England’s lost rows.
Check Yourself
Every cell runs after import pandas as pd. Say your answer before you type it. The first one is from L19.
Find the SD of 2, 6, 10, 13, 14 by hand. L19
- Mean: 45 ÷ 5 = 9.
- Minus the mean: −7, −3, 1, 4, 5.
- Squared: 49, 9, 1, 16, 25. Add: 100.
- Divide by n − 1 = 4: 25.
- Square root: √25 = 5.
Say this line in English: temps = pd.Series([47, 52, 50])
Rule 2: = means “call it”, so the line names something and shows nothing. pd.Series is the Series tool inside pandas: it makes a column.
What is the Sheets twin of .median()?
From the translation table: =MEDIAN is .median(), the middle value once they are in order.
What does line 2 print?
1nums = pd.Series([2, 4, 9])
2print(nums.mean())
In Sheets this is: =AVERAGE on three numbers. In English: 1. Make a column of the three numbers, and call it nums. 2. Print the mean of nums.
2 + 4 + 9 = 15, and 15 ÷ 3 = 5. pandas keeps every mean as a decimal, so it prints 5.0.
Same nums. What does this line print?
1print(len(nums))
In Sheets this is: counting the rows. In English: Print how many numbers nums has.
nums holds 2, 4 and 9: three numbers. len( ) counts them, so it prints 3.
Change one word: .mean() becomes .max(). What does it print now?
1print(nums.max())
In Sheets this is: =MAX. In English: Print the largest number in nums.
The largest of 2, 4 and 9 is 9. Every number in nums is whole, so it prints 9 with no .0.
Quiz marks typed into a Sheet: one box is empty and one says "13 cm". What does line 3 print?
1raw = pd.Series(["9", "", "11", "13 cm", "10"])
2marks = pd.to_numeric(raw, errors="coerce")
3print(marks.count())
In Sheets this is: fixing "13 cm" and blanks by hand, then counting what is left. In English: 1. Make a column of the five things typed, as text, and call it raw. 2. Keep the numbers in raw; anything else becomes blank. Call the result marks. 3. Print how many numbers marks has.
"9", "11" and "10" are numbers. The empty box and "13 cm" become blank, and .count() skips blanks. It prints 3. (Their mean would print 10.0.)
A cell shows a red error. Its last line says name 'df' is not defined. What happened?
df is made in Cell 2, the one that opens the file. Rule 1: a line can use only what an earlier line made. Run Cell 2, then try again. (A changed column name gives a KeyError instead.)
Project Checkpoint
Check your P2 numbers in Python
Python reads every row of your file and gives the same numbers your Sheet does. When the two agree, you can trust both. When they differ, a row is off, and now you know where to look.
Once your CLEAN tab exists (L22, Fri 4 Dec):
Run this cell and choose the CSV you downloaded. It is read on this computer and sent nowhere.
In Sheets this is: LOG's =COUNTA(CLEAN!C2:C), then ANALYSIS B11 to B14: =COUNT, =AVERAGE, =MEDIAN and =STDEV of CLEAN!B:B.
In English:
- Get the tool that opens files.
- Get the pandas toolbox and call it pd.
- Show a Choose file button, and call the name of the file you pick name.
- Open the file as a table called df.
- Take the number column, keep only the numbers, and call it n.
- Print how many rows.
- Print how many numbers.
- Print the mean rounded to 2 places, the median, and the SD rounded to 2 places.
Predict: LOG D2 and ANALYSIS B11 to B14 already hold these. Which will match? If rows and numbers differ, that many rows have no number.
Tick each step once it is in your Sheet. Your ticks go into the PDF you hand in. Where everything goes: your Sheet, tab by tab.
Read More
pandas, “How to calculate summary statistics”, from pandas’ own getting started tutorials. Read the first part, Aggregating statistics. It uses a file of Titanic passengers: titanic["Age"].mean() is the mean age, with the same .mean() you read here. Every line there follows the six rules.
Stuck on any of this? Ask Mr. Case in class or send him a message in Canvas. Copy the line of code that lost you into the message.