Chapter 3 Exercises — Python and pandas for Cricket

Difficulty: ⭐ conceptual · ⭐⭐ calculation and short code · ⭐⭐⭐ multi-step analysis and judgement · ⭐⭐⭐⭐ open-ended research

All code exercises assume the chapter header (toolkit and project on the path) and use the book's data snapshot (Cricsheet, through November 2026). Short answers to Part B are in <details> blocks; selected answers to other parts are in Appendix I.


Part A — Conceptual ⭐

A1. In your own words, explain the difference between a variable, a list and a dictionary, using one cricket example of each that is not from the chapter.

A2. Python counts list positions from 0. A cricket over counts balls from 1. Write down last_over[0], last_over[3] and last_over[-1] for last_over = [1, 0, 4, 1, 6, 0], and say which ball of the over each one is.

A3. Why does the book define balls faced to exclude wides but include no-balls? Give the cricketing reason, not just the rule.

A4. The chapter's batting_strike_rate function returns None when balls == 0. A friend suggests returning 0 instead "so the leaderboard doesn't break". Explain what would go wrong in a leaderboard sorted by strike rate if you followed that advice.

A5. Explain "split–apply–combine" using the example of finding the number of sixes hit by each team in a season. Say exactly what is split, what is applied, and what the combined result looks like.

A6. What is the difference between merge(..., how="left") and merge(..., how="inner")? Describe a cricket situation where choosing the wrong one would silently drop matches from your analysis.

A7. The wicket_kind column is missing on about 95% of IPL deliveries. Explain why that is information, not a data-quality problem, and name one column in the matches table where a missing value genuinely is a gap in the data.

A8. Give two reasons why a Python for loop over the rows of a DataFrame (iterrows) is a bad way to compute a season's strike rates, and one situation in the chapter where a loop was the right tool.

A9. "A result with zero rows is not an answer." Give two different bugs from the chapter that produce an empty or wrong result without raising an error.

A10. The chapter shows the IPL 2026 death-overs run rate as 10.32 in one place and 10.79 in another. Without looking back, explain how both can be correct.


Part B — Calculation & Interpretation ⭐⭐

B1. In the IPL 2025 final, Kohli faced 35 balls: 4 dots, 25 singles, 3 twos and 3 fours (check: 25 + 6 + 12 = 43). (a) What percentage of his balls were dots? (b) What percentage of his runs came in boundaries? (c) Compare (b) with his IPL career boundary-run percentage of 56.47 (book data). What does the comparison say about how he played that innings?

Answer

(a) 4 / 35 = 11.4%. (b) 12 / 43 = 27.9%. (c) In the final, barely 28% of his runs came in boundaries against 56.47% across his IPL career — about half his usual share. He scored that innings by running, not hitting: a deliberate, low-risk rotation innings rather than his normal mix. (Whether that was the right approach in a final where his team made 190 is a judgement — Chapter 9 gives you tools to measure it.)

B2. In IPL 2026, the powerplay had 5,278 legal balls with a dot percentage of 41.4% and a boundary percentage of 26.7%; the middle overs had 7,755 legal balls at 28.4% dots and 18.8% boundaries. (a) Roughly how many dot balls and how many boundaries were there in each phase? (b) What percentage of powerplay legal balls were neither a dot nor a boundary, and what does that say about the powerplay game?

Answer

(a) Powerplay: about 0.414 × 5,278 ≈ 2,185 dots and 0.267 × 5,278 ≈ 1,409 boundaries. Middle: about 0.284 × 7,755 ≈ 2,202 dots and 0.188 × 7,755 ≈ 1,458 boundaries. (b) 100 − 41.4 − 26.7 = 31.9% in the powerplay (singles, twos, threes) — against 100 − 28.4 − 18.8 = 52.8% in the middle overs. The powerplay is a feast-or-famine phase: over two-thirds of legal balls are either nothing or a boundary.

B3. Jasprit Bumrah's IPL death-overs record in the data: 1,423 legal balls, 1,943 runs, 102 wickets. Compute his death economy, bowling average and bowling strike rate (balls per wicket). Then compute how many runs more he would have conceded over those balls at the 2026 league death run rate on legal balls (10.32 an over).

Answer

Economy = 6 × 1,943 / 1,423 = 8.19. Average = 1,943 / 102 = 19.05. Strike rate = 1,423 / 102 = 13.95 balls per wicket. At 10.32 an over, 1,423 balls would cost 10.32 × 1,423 / 6 ≈ 2,448 runs — about 505 more than he conceded. (Caveat: his career spans eras with lower scoring than 2026, so this exaggerates the gap; comparing each season with that season's rate is the fair version — an exercise in Part C.)

B4. From the chapter: in 2026, 200+ first-innings totals were defended 20 times out of 37; across 2008–2026, 161 times out of 212. (a) Compute both percentages. (b) How many 200+ totals were successfully chased down across 2008–2025 (i.e. excluding 2026)?

Answer

(a) 20/37 = 54.1%; 161/212 = 75.9%. (b) Across 2008–2025: 212 − 37 = 175 totals, defended 161 − 20 = 141, so chased down 175 − 141 = 34 times (19.4%). In 2026 alone, 17 were chased down — half as many as in the previous eighteen seasons combined.

B5. The Women's Premier League table showed Ellyse Perry with 972 runs and 15 outs in 25 innings, and Smriti Mandhana with 1,023 runs and 33 outs in 35 innings. (a) Compute both averages. (b) Perry's balls faced were 731; Mandhana's 748. Compute both strike rates. (c) Which single number would you show a selector, and why is neither enough?

Answer

(a) Perry 972/15 = 64.80; Mandhana 1,023/33 = 31.00. (b) Perry 100 × 972/731 = 132.97; Mandhana 100 × 1,023/748 = 136.76. (c) Neither alone: Perry's average is more than double Mandhana's, but she was dismissed far less often per innings (15 outs in 25 innings — she was often not out, which inflates average), while Mandhana scores slightly faster and bats at the top where dismissals are more frequent. A selector needs runs per innings, strike rate, role (batting position and phase) and sample together — Chapter 4 explains how not-outs inflate averages.

B6. The chase table for the IPL 2025 final shows Punjab needing 55 off 24 with 6 wickets in hand after 16 overs, and 47 off 18 with 4 in hand after 17. (a) Compute the required run rate at each point. (b) Which changed more in that over — the required rate or the resources (balls and wickets) left? Explain in one sentence why a fan's instinct and a scoreboard's required-rate number can disagree about how big a moment that over was.

Answer

(a) After 16: 6 × 55/24 = 13.75 per over. After 17: 6 × 47/18 = 15.67 per over. (b) The required rate rose by about 1.9 an over, but the resources fell sharply — six balls and two wickets, a third of the remaining wickets. The scoreboard's required rate ignores wickets entirely, while a fan watching two set or new batters fall knows the chase is now in the tail's hands; win-probability models (Chapters 9 and 20) are built precisely to combine the two.

B7. Kohli's IPL career: 6,926 balls faced (wides excluded) and 9,336 runs. If you wrongly count the 197 wides he was on strike for as balls faced, what strike rate do you get? Show the arithmetic and match it to the chapter's output.

Answer

Correct: 100 × 9,336 / 6,926 = 134.80. Wrong: balls = 6,926 + 197 = 7,123; 100 × 9,336 / 7,123 = 131.07. The chapter's script prints exactly these two numbers. (Runs off the bat on a wide are always zero, so the numerator does not change — only the denominator is wrong.)

B8. In the 2025 Women's World Cup (Case Study 2), Laura Wolvaardt scored 571 runs off 578 balls with 8 dismissals in 9 innings, and Ash Gardner 328 off 252 with 4 dismissals in 5 innings. (a) Compute runs per innings, average and strike rate for both. (b) If Gardner had batted four more innings at her tournament runs-per-innings rate, how many runs would she have finished with? (c) Why is (b) a dangerous calculation to publish?

Answer

(a) Wolvaardt: 571/9 = 63.4 runs per innings; average 571/8 = 71.38; SR 100 × 571/578 = 98.79. Gardner: 328/5 = 65.6 per innings; average 328/4 = 82.00; SR 100 × 328/252 = 130.16. (b) 328 + 4 × 65.6 ≈ 590 — more than Wolvaardt's 571. (c) It assumes five innings are a reliable guide to the next four, which they are not; it ignores who Australia would have played and in what conditions; and it is a counterfactual dressed as a statistic. It is a fair illustration of how much aggregates depend on opportunity, and an unfair claim about who was better.


Part C — Code It ⭐⭐–⭐⭐⭐

C1. Build this metric — boundary-to-dot ratio. ⭐⭐ Using IPL 2026 deliveries (no super overs, no wides), compute for every batter with at least 150 balls faced: fours, sixes, dots, and the ratio boundaries ÷ dots. (batting_summary already gives you fours, sixes, dots and balls — you need one new column and one filter.) Output: a DataFrame of the top 10 by ratio, with columns balls, boundaries, dots, ratio, sorted descending. Then write two sentences on what this metric rewards and what it misses.

C2. Evaluate this player — Bumrah by season, against the league. ⭐⭐⭐ Extend B3. For each IPL season Jasprit Bumrah played, compute his death-overs economy (bowling_summary on his death deliveries, by=["bowler", "season"]) and the whole league's death run rate that season (all runs ÷ legal balls × 6). Output a table with columns season, balls, economy, league_death_rr, difference and a line chart of the two rates by season. Which season was his best relative to the league?

C3. Analyze this match — any final, any competition. ⭐⭐ Use explore.find_matches(games, stage="Final") on the Big Bash ("bbl") or PSL ("psl") and pick the most recent final in the data. Print its scorecard with explore.format_scorecard and its over-by-over table. Write a 150-word match report that uses at least four numbers from the output and identifies the over where the result turned.

Hint: add need, balls_left and required_rr columns to the second innings of over_by_over exactly as Case Study 1 does. "The over where the result turned" is a judgement — defend yours with the change in required rate and wickets in that over.

C4. Build this metric — the "maiden-ish" over. ⭐⭐⭐ Modify bowling_card (copy it into your own script; do not edit the project file) to also count overs in which the bowler conceded 3 runs or fewer off six legal balls. Run it across all IPL 2026 deliveries (group by bowler across the season) and list the five bowlers with the most such overs, with their total overs bowled. Why is this more informative than maidens in modern T20?

Expected shape: a DataFrame indexed by bowler with columns overs_bowled, tight_overs, tight_pct, sorted by tight_overs descending, five rows. Hints: group by ["bowler", "match_id", "innings", "over"] (an over number repeats across matches, so over alone is not a key), compute runs conceded and legal balls per group, then flag (runs <= 3) & (legal == 6). Add a reconciliation line: the sum of overs_bowled across all bowlers should equal the season's legal balls ÷ 6, give or take incomplete overs.

C5. Settle this debate — do teams batting first in the WPL win more often than in the IPL? ⭐⭐⭐ Using explore.innings_totals for both competitions, compute (for matches with a winner and no D/L) the share won by the side batting first, by season. Output a table with one row per season per competition. Then answer the debate in three sentences, mentioning sample sizes.

Expected shape: a long table with columns competition, season, decided_matches, batting_first_wins, batting_first_win_pct — four WPL rows and nineteen IPL rows. Hint: the WPL has 22 matches a season in the data, so one or two results swing its percentage by about five points; say so. A tidy way to build the table is to write one function that takes (balls, games, label) and returns the per-season frame, call it twice, and stack the results with pd.concat.

C6. Optimize this strategy — when should a captain bowl their best death bowler? ⭐⭐⭐ For IPL 2024–2026, compute the league run rate (all runs ÷ legal balls × 6) and wicket rate for each individual over number 1–20. Plot both against over number on the same figure (two y-axes or two panels). From the chart alone, which two overs are the most expensive, and what would you advise a captain who has to choose between using a gun bowler in the 17th or the 19th over? (You will revisit this properly in Chapter 31.)

Expected shape: a 20-row DataFrame indexed by over with columns legal_balls, runs, run_rate, wickets, wicket_pct, and one figure saved to your own images/ folder. Hints: use all deliveries for runs but is_legal for the ball count; exclude super overs; restrict seasons with balls["season"].isin(["2024", "2025", "2026"]) (text!). Before advising the captain, note what the chart cannot show: the run rate in the 19th over depends on who bowls it, so the league average mixes the best and worst death bowlers.

C7. Predict this match — a first, naive lookup. ⭐⭐⭐ Reuse the state_after_15 function from code/case_study_01.py on IPL data. Build a table of chase win percentage by need band (≤20, 21–30, 31–40, 41–50, 51–60, 61+) and wickets lost after 15 overs (0–2, 3–4, 5–6, 7+). Print the table and the count in each cell. Which cells would you refuse to quote, and why?

Expected shape: two 6 × 4 grids from pivot_table — one of win percentages, one of counts — with need bands as rows and wicket bands as columns. Hints: make the bands with pd.cut(s["need"], [-100, 20, 30, 40, 50, 60, 400], labels=[...]) and similarly for wickets; use aggfunc="mean" on chaser_won for one grid and aggfunc="size" for the other. Decide a minimum count (say 20) below which a cell is printed as missing, and explain your choice. You have just built a crude version of the win-probability lookup table that Chapter 9 constructs properly.

C8. Evaluate this player — an innings, ball by ball, without pandas. ⭐⭐ Practise the plain-Python half of the chapter. Pick any innings of at least 30 balls from the 2026 IPL final (match 1535465 — Kohli's 75 not out off 42 is a good choice). Extract the runs off the bat for each ball faced with one pandas line (.tolist()), and from then on use only lists, loops and functions: (a) count dots, singles, twos, fours and sixes with a loop; (b) write a function fastest_ten(runs) that returns the 10-ball window with the most runs and the ball numbers where it started and ended; (c) build the running total and report the ball on which the batter reached 50. Expected output: five counts that sum to the balls faced, one window (start, end, runs), one ball number. Then check (a) against batting_summary on the same rows — they must agree.


Part D — Judgment & Format Transfer ⭐⭐⭐

D1. The chapter's phase_table uses powerplay/middle/death. Would the same function work on Test-match deliveries? What does the toolkit put in the phase column for Tests, and what would you group by instead to get a meaningful "phase" view of a Test innings?

D2. season_summary reports "average first-innings total in matches with a winner and no D/L revision". Is that the right filter for an ODI tournament like the 2025 Women's World Cup (see Case Study 2)? Argue both sides: what does the filter protect against, and what real cricket does it throw away?

D3. Eye test v data. Wendell says the scorecard of the 2025 final "tells me which overs to go and watch again". List three questions about that match that the ball-by-ball data cannot answer and that the video can, and one question the data answers better than anyone's memory of the match.

D4. A fantasy-cricket friend shows you a leaderboard of "best IPL strike rates in 2026" with a batter at the top who faced 11 balls. Write the reply you would send, including a code line that would fix the leaderboard and a sentence on why a fixed cut-off (say 150 balls) is itself a compromise.

D5. Team names change (Bangalore → Bengaluru, Kings XI Punjab → Punjab Kings, Delhi Daredevils → Delhi Capitals). Is "Delhi Daredevils 2008–2018" and "Delhi Capitals 2019–2026" the same team for analytical purposes? Give one analysis where you would merge them and one where you would not.

D6. The chapter's format_scorecard works unchanged on a T20 and on an ODI (Case Study 2). Name two things a Test scorecard needs that the function does not produce (think about innings, declarations, follow-ons and the length of a match), and say which toolkit columns would help you add them.


Part M — Mixed / Interleaved ⭐⭐–⭐⭐⭐

M1. (Chapters 1 and 3) ⭐⭐ Chapter 1 said Kohli's IPL career death-overs strike rate (188.38) is higher than Suryakumar Yadav's (178.21), even though Suryakumar's overall strike rate is higher. Verify both numbers yourself with explore.phase_table, then extend the table to the 2024–2026 seasons only. Does the story hold in the Impact Player era?

M2. (Chapters 2 and 3) ⭐⭐ Chapter 2 explained that the toolkit flattens Cricsheet's JSON and that some details are lost. This chapter found one (substitute fielders and Impact Player swaps). Open the raw JSON for match 1473511 (inside data/raw/ipl_json.zip) with Python's zipfile and json modules and print the replacements entries. Then count, across all IPL 2023–2026 matches, how many recorded an impact_player replacement for each team.

M3. (Chapters 1 and 3) ⭐⭐⭐ Chapter 1 used the IPL's average first-innings total as evidence that the game is changing faster than its statistics. Use explore.season_table to produce the same series for the Big Bash and the PSL. Plot all three leagues on one chart by calendar year. Is the "scoring revolution" an IPL phenomenon or a T20 phenomenon?

M4. (Chapters 2 and 3) ⭐⭐ Chapter 2 introduced the people register (load_people). Merge it with an IPL 2026 batting leaderboard so that each batter has an identifier you could use to look them up on another site. How many of the top 50 run-scorers fail to match on name, and why might that be?

M5. (Chapters 1, 2 and 3) ⭐⭐⭐ Write a single script, my_season_report.py, that takes a competition code and a season as command-line arguments (sys.argv) and prints: the season summary, the top-5 batters and bowlers (with minimums you choose and state), and the final's scorecard if there was a final. Run it for three competitions, at least one of them women's.

M6. (Chapters 1 and 3) ⭐⭐⭐ Chapter 1 introduced the turning-point match of this book: South Africa v Sri Lanka, 3rd T20I, Cape Town, 25 January 2017 (Cricsheet id 936157 in t20s_male). Use explore.format_scorecard and explore.over_by_over to rebuild it. Confirm from your output the score after 15 overs of the chase and what happened in the 16th over, then compute the chase's need and balls_left after every over. Save the table — Chapters 9 and 20 will attach win probabilities to exactly these rows.


Part E — Research & Extension ⭐⭐⭐⭐

E1. A women's T20 World Cup in one DataFrame. Using t20s_female, identify every match of the most recent Women's T20 World Cup in the data (check the event_name values and the season labels carefully). Rebuild its leaderboards, the final's scorecard, and a phase run-rate table for the tournament. Compare the tournament's phase profile with the WPL's. Write up 800 words with at least two figures. Be explicit about sample sizes: a 20-over World Cup is a handful of matches per team, and any phase number for a single player will rest on a few dozen balls at most. Where the tournament overlaps with a no-result or a D/L match, say how you handled it.

E2. How clean is the data, really? Pick one league other than the IPL ("bpl", "lpl", "cpl" or "ntb"). Systematically audit its matches table: missing cities, missing winners and why, team-name changes, season labels, matches with fewer than 200 deliveries, D/L matches. Produce a one-page "data quality card" for the league that a future analyst could rely on, with every number computed. Finish with three "rules for using this league's data" in the style of the five rules at the end of Chapter 3 — for example, how to filter its seasons safely and which of its teams changed names.

E3. Extend the project. Add a function head_to_head(balls, matches, team_a, team_b) to your own copy of explore.py (keep the original untouched) that returns the two teams' record against each other — matches, wins each, no-results, average first-innings total — handling team-name changes through an explicit mapping dictionary. Test it on two IPL franchises across the Bangalore/Bengaluru rename.