Chapter 3 Notes — Python and pandas for Cricket
Chapter link: Chapter 3
Overview and learning objectives
Chapter 3 teaches Python and pandas from the first line, with every idea attached to a cricket question. It opens with Shashank Singh's last over in the IPL 2025 final — sum([0, 0, 6, 4, 6, 6]) returns 22, not enough as Royal Challengers Bengaluru (190/9) beat Punjab Kings (184/7) by six runs — and finishes by rebuilding that final's full scorecard from its 252 deliveries. Along the way: variables, lists, loops, dictionaries and functions; DataFrames; filtering; groupby; merge and pivot_table; missing values, messy labels and dates; reading tracebacks; and the silent bugs that never crash. The Crease module is explore.py (scorecards, over-by-over tables, leaderboards, phase tables, season summaries).
By the end of the chapter students should be able to:
- Represent an over as a list and a scorecard line as a dictionary, and write a strike-rate function that handles zero balls honestly (returning
None, not 0). - Load a competition and filter it with combined conditions using
&,|,~and.isin()with brackets around each condition. - Build a leaderboard with
groupbyand named aggregation, with a stated minimum sample. - Merge innings totals with match results and reshape with
pivot_table(e.g. top-10 batters × phase strike rates). - Diagnose and fix at least five common tracebacks by reading the last line first.
- Identify the four silent bugs (season as text, wides in balls faced, super overs, empty filters) and test for each.
- Rebuild any match's scorecard with
explore.format_scorecard()and reconcile it to the total.
Where students struggle
- Absolute beginners and the first hour. Expect a wide spread. Students who have never coded need the §3.1–3.3 material typed, not copied. Experienced coders should skip to §3.4.
andversus&, and missing brackets.balls["phase"] == "death" & balls["season"] == "2026"produces the bafflingTypeError: Cannot perform 'rand_'. Drill "brackets around every condition".runs_totalversusruns_batterversus runs conceded. Wrong by a few percent and plausible — the most dangerous kind of wrong.- Two run rates for the same phase. IPL 2026 death overs: 10.32 on legal balls only (extras dropped) v 10.79 using all runs over legal balls (Exercise A10). Students think one is a mistake.
- Season as text.
season == 2026returns 0 rows;season == "2020"returns 0 rows because IPL 2020 is"2020/21". - Wides in balls faced. Kohli's IPL strike rate becomes 131.07 (7,123 "balls") instead of 134.80 (6,926) — no error raised.
SettingWithCopyWarning. Installed pandas is 2.3.x, so students will see it; tell them.copy()after filtering a table they intend to modify. (In pandas 3 the warning disappears.)- Loops. Students coming from other languages reach for
iterrows. The chapter timed it at 5.211 s versus 0.048 s forgroupbyon the book's machine (about 109×; machine-dependent).
Pacing
This chapter is best taught as two sessions plus a lab for beginners; one session for experienced programmers.
50-minute session (session 1 of 2).
- 0–5: Shashank's over as a list.
- 5–20: Variables, lists, loops, dictionaries, functions (§3.1–3.3); the zero-balls Productive Struggle.
- 20–35: DataFrames and filtering (§3.4–3.5); the runs_total pitfall.
- 35–50: groupby and leaderboards with minimums (§3.6).
50-minute session (session 2 of 2). merge and pivot_table (15), missing values and dates (10), tracebacks and silent bugs (15), scorecard rebuild (10).
75-minute session (single-session version for programmers). §3.4–3.10 with a 20-minute live coding segment on the silent bugs and a 10-minute "Settle this debate" on 200 batting first.
Lab time: 90 minutes minimum: typing §3.1–3.3, then building one leaderboard and one scorecard.
Lecture outline
- From
sum(last_over)to a scorecard: the load → filter → group → merge/reshape → check → plot workflow. - Python basics with cricket: a batter in three variables; an over as a list (0-based positions, 1-based balls); loops through an innings; a scorecard line as a dictionary; a strike-rate function.
- DataFrames: 295,732 IPL deliveries; a column is a Series;
runs_totalvruns_batter. - Filtering: one bowler in one phase (Bumrah at the death: 1,423 legal balls, economy 8.19, 102 wickets); what happens on a ball, phase by phase (IPL 2026 legal balls: powerplay dots 41.4%, boundaries 26.7%).
groupby: named aggregation; leaderboards need minimums; same code, different competition (WPL).mergeandpivot_table: innings totals with results; the 200-batting-first debate; the phase heatmap.- Missing values, messy labels and dates (team-name changes;
winnermissing for 16 ties and 9 no-results; IPL 2020 played September–November). - Tracebacks, read bottom-up; the bugs that don't crash.
- The 2025 final rebuilt; Wendell's "tells me which overs to go and watch again".
Live coding demo — "Break it on purpose"
Script: code/05_errors_and_tracebacks.py, then code/07_try_it.py.
- Run
05_errors_and_tracebacks.pyand read one full traceback bottom-up (TypeError: can only concatenate str (not "int") to str). - Live, type the broken filter
balls["phase"] == "death" & balls["season"] == "2026"and let it fail; fix it with brackets. - Show the silent bugs the script prints:
games[games['season'] == 2026] -> 0 rows,== '2026' -> 74 rows; Kohli 7,123 balls / SR 131.07 with wides v 6,926 / 134.8 without. - Run
07_try_it.pyfor the 200-batting-first table. Expected: 2026 37 totals, 20 defended (54.1%); 2008–2026 212 totals, 161 defended (75.9%); 2024–26 win rate by band <180 0.130 (77), 180–199 0.487 (39), 200–219 0.617 (47), 220+ 0.750 (48). - Live change: edit the bands (e.g. split 220+ into 220–239 and 240+) and ask students to predict before running. Do not promise numbers; point out how small the new cells become.
In-class activity — "Scorecard detectives"
Pairs run explore.format_scorecard() on the IPL 2026 final (find it with explore.find_matches(games, season="2026", stage="Final")). Known values to check: Gujarat Titans 155/8; Royal Challengers Bengaluru 161/5 in 18 overs; Kohli 75* off 42. Each pair must (a) reconcile bowlers' runs plus byes and leg-byes to the total, (b) identify the over in which the chase broke open, and (c) write one question Wendell would ask that the scorecard cannot answer. Ten-minute share-out.
Answers and teaching notes for key exercises
- A10. 10.32 uses legal balls only, so runs from wides and no-balls fall out of the numerator; 10.79 sums all runs and divides by legal balls. Each answers a different question.
- B1. Dots 4/35 = 11.4%; boundaries 12/43 = 27.9% of runs, against Kohli's IPL career 56.47% — he played the 2025 final as a running innings.
- B3. Bumrah at the death: economy 8.19, average 19.05, strike rate 13.95; at 10.32 an over he would concede ≈ 2,448 runs, about 505 more. Stress the caveat: comparing a career with one season's rate exaggerates the gap.
- B4. 54.1% and 75.9%; 2008–2025: 175 totals, 141 defended, 34 chased (19.4%); in 2026 alone 17 were chased.
- B6. Required rate 13.75 after 16 overs, 15.67 after 17. The rate rose about 1.9 an over, but two wickets fell — the scoreboard rate ignores wickets, which is why Chapters 9 and 20 build win probability.
- B8. Wolvaardt 63.4 per innings, average 71.38, SR 98.79; Gardner 65.6, 82.00, 130.16; projecting Gardner over four more innings gives ≈ 590 — a fair illustration of opportunity, an unfair claim of superiority.
Assessment ideas
- Code task: "Most sixes in the 2024 IPL" using load → filter → groupby, with a row-count check after each step.
- Debugging task: give students three broken snippets (missing brackets, season as integer, wides in balls) and ask for the fix and the symptom.
- Short write: the 200-batting-first debate in 150 words, quoting the 2026 and all-time defence rates.
- Learning check-in: collect students' answers to the 🪞 prompt ("which silent bug are you most likely to commit?") as a formative check.
Format, gender and region diversity notes
- The WPL Try it uses Mandhana's season-by-season strike rate (111.19 → 133.93 → 136.81 → 153.25) and phase profile (powerplay 122.18 v middle 160.32), compared with Sciver-Brunt, Harmanpreet and Shafali. Use it as a main example.
- WPL all-time leaders: Sciver-Brunt 1,348 runs (avg 49.93, SR 144.02). Exercise B5 (Perry v Mandhana) previews not-out inflation.
- Case Study 2 is the 2025 Women's ODI World Cup (Wolvaardt 571 runs; Deepti Sharma 22 wickets; India beat South Africa in the final by 52 runs) — an ODI and a women's example in one.
- Case Study 1 is the 2024 men's T20 World Cup final (India beat South Africa by 7 runs).
- Nusrat learns on an old laptop in Dhaka: model the course for students with low-spec hardware (load only needed columns; avoid loops).
Connections
- Data and toolkit behind every line: Chapter 2.
- What to distrust in the statistics students can now compute: Chapter 4.
- Sample minimums and Mandhana's jump: Chapter 6.
- Worms and Manhattans built properly: Chapter 7.
- The required rate versus win probability (Exercise B6): Chapter 9 and Chapter 20.
- Python reference: Appendix A.