The 2026 IPL final, Narendra Modi Stadium, Ahmedabad, 31 May 2026. Royal Challengers Bengaluru win the
In This Chapter
- Nine rows for six balls
- 2.1 Where cricket data comes from
- 2.2 Setting up your toolkit
- 2.3 Anatomy of a Cricsheet match file
- 2.4 The toolkit, line by line (I): constants, download, phases
- 2.5 The toolkit, line by line (II): parse_match() turns a tree into rows
- 2.6 The toolkit, line by line (III): build(), the cache, and load_*
- 2.7 The toolkit, line by line (IV): the canonical summaries
- 2.8 What's in the snapshot — and an audit before you trust it
- 2.9 Names are not identities: the people register
- 2.10 What Cricsheet can't tell you
- 2.11 First analysis: the leaders of IPL 2026 and WPL 2026
- Project Checkpoint: data.py
- Chapter Summary
- What's Next
Chapter 2 — Cricket Data: Sources, Formats, Ball-by-Ball Records, and Building Your Analytical Toolkit
Nine rows for six balls
The 2026 IPL final, Narendra Modi Stadium, Ahmedabad, 31 May 2026. Royal Challengers Bengaluru win the toss and bowl. Jacob Duffy runs in to B. Sai Sudharsan. Dot. Dot. Four. Four. Then a wide. Then another wide. Then a single. Shubman Gill on strike: a wide, and a single to finish.
On television that was "over one, thirteen runs." In the data it is nine rows. Six legal deliveries, three wides, each a separate event with its own batter, bowler, non-striker and runs. If you count rows and call it balls, you have already miscounted the first over of the most important match of the season. And one of those wides carries something extra: a review. Gujarat Titans asked the third umpire to look at a decision against Sai Sudharsan; the delivery stands in the record as a wide, no wicket, with the review attached to it like a sticky note.
Eighteen overs later Virat Kohli hit Arshad Khan for six to finish the chase. Royal Challengers Bengaluru 161 for 5 in 18 overs, chasing 156; Kohli 75 not out off 42 balls, nine fours and three sixes; player of the match. Gujarat Titans' 155 for 8 had been held together by Washington Sundar's 50 not out off 37.
Every one of those numbers — the 13-run over, the 75 off 42, the 18 overs, Rasikh Salam's 3 for 27 —
you will compute yourself in this chapter, from a free file you can download in Dhaka, Port of Spain
or Leeds. Here is the first over as the book's toolkit flattens it (the full output is in
code/02_parse_and_cache.py):
First over of the final, flattened:
innings over ball_in_over legal_ball_index batter bowler runs_batter runs_extras wides is_legal is_wicket phase
1 1 1 1.0 B Sai Sudharsan JA Duffy 0 0 0 True False powerplay
1 1 2 2.0 B Sai Sudharsan JA Duffy 0 0 0 True False powerplay
1 1 3 3.0 B Sai Sudharsan JA Duffy 4 0 0 True False powerplay
1 1 4 4.0 B Sai Sudharsan JA Duffy 4 0 0 True False powerplay
1 1 5 NaN B Sai Sudharsan JA Duffy 0 1 1 False False powerplay
1 1 5 NaN B Sai Sudharsan JA Duffy 0 1 1 False False powerplay
1 1 5 5.0 B Sai Sudharsan JA Duffy 1 0 0 True False powerplay
1 1 6 NaN Shubman Gill JA Duffy 0 1 1 False False powerplay
1 1 6 6.0 Shubman Gill JA Duffy 1 0 0 True False powerplay
Look at the ball_in_over column. Three rows say "5". That is not a bug; it is a decision — the
toolkit labels each delivery with the legal ball being bowled, so the two wides before the fifth
legal ball are both "ball 5 attempts". The legal_ball_index column is blank (NaN, "not a number",
pandas' marker for a missing value) on the wides, because a wide does not advance the innings' count
of legal balls. Two columns, two different questions: "which ball of the over was this attempt at?"
and "how many legal balls have been bowled?"
This chapter is about decisions like that. Before you can say anything true about a batter's strike
rate or a bowler's economy, somebody has to decide what a "ball" is, what a "run" is, who "faced" a
wide, which team was bowling in a super over, and what to do when the umpire miscounts and an over
has seven deliveries. In most cricket statistics those decisions are invisible. In this book they are
written down in one file, toolkit/cricdata.py, and by the end of this chapter you will have read
every line of it.
🏏 Fan Track: Read the hook, §2.1 (where data comes from), §2.3 (what a match file looks like), §2.10 (what the data can't tell you) and §2.11 (the 2026 leaders). Skim the code; the prose carries the argument.
📊 Analyst Track: Everything, with the toolkit open beside you. §2.4–§2.7 are the line-by-line reading; §2.8 is the data audit you should run on any new dataset. Do Exercises C1–C6.
🧑💼 Franchise Track: §2.1, §2.7 (canonical definitions — the numbers your analysts quote), §2.8 (where the data is wrong or missing) and §2.10 (why the Hawk-Eye feed you may license changes the picture).
2.1 Where cricket data comes from
The cricket question: if you want to know how many runs Smriti Mandhana scored in the 2026 WPL, or how often Test batters are out lbw, where do you look — and can you trust the answer?
Cricket has kept records for longer than almost any sport. The scorebook — the grid of dots, figures and wicket symbols kept by a scorer in the pavilion — is a ball-by-ball record, and has been for well over a century. The trouble has never been that the data didn't exist. It is that it lived on paper, in thousands of scorebooks, and the summaries that reached the public were aggregates: a batter's career runs, innings, not-outs and average; a bowler's wickets and economy. Every ball-level detail — which over, which bowler, the score at the time — was thrown away on the way to the newspaper.
Today you have four broad kinds of source. Know what each is good for.
| Source | What it is | Granularity | Cost / access | What it's good for |
|---|---|---|---|---|
| Cricsheet | Free ball-by-ball data files for thousands of matches, maintained by Stephen Rushe | Every delivery | Free download, open licence | The foundation of this book: anything you compute ball by ball |
| ESPNcricinfo Statsguru | The query engine behind ESPNcricinfo's records pages | Mostly innings- and match-level, with long historical depth | Free to browse on the web; no official bulk download | Career and innings records going back to the 19th century; checking your numbers against the reference most journalists use |
| Howstat | A long-running statistics website focused on Test and ODI records | Innings and match level | Free to browse | Historical Test and ODI records, scorecards, lists |
| CricketArchive | A large subscription database of scorecards at every level, including domestic and minor cricket | Scorecards | Subscription for much of it | Obscure players, domestic and lower-level matches |
| Ball-tracking (Hawk-Eye and similar) | Camera-based tracking of every delivery's speed, line, length, bounce and trajectory | Every delivery, with physical measurements | Not public — sold to broadcasters, boards and teams | Pitch maps, release points, swing, DRS — the material of Chapter 15 |
We will describe the web databases honestly and not pretend to know their internals. What matters for an analyst is the difference in granularity — the level of detail a dataset records. Statsguru can tell you a batter's average in matches their team won; it cannot easily tell you their strike rate in overs 16–20 of a chase, because that requires every ball. Cricsheet can.
Cricsheet
Cricsheet is a one-person project — Stephen Rushe has maintained it for years — that publishes
ball-by-ball records of men's and women's internationals and of most major domestic T20 leagues as
free downloads, in JSON (and other) formats. Every archive in this book's snapshot carries a
LICENSE.txt file, and the first line of it reads:
# ODC Attribution License (ODC-By)
The Open Data Commons Attribution License lets you use, share and modify the data, including commercially, as long as you attribute the source. If you publish an analysis built on this book's data, credit Cricsheet. That is the whole obligation, and it is a small price for the most useful free dataset in the sport. (Read the licence text in the archive itself; this paragraph is a summary, not legal advice.)
Cricsheet's coverage is not "everything". Two limits you must know on day one:
- Coverage starts when Cricsheet's sources start. Men's Tests in this snapshot begin in December 2001; men's ODIs in June 2002; the IPL from its first match in April 2008. Bradman is not in here. For the 19th and most of the 20th century you need Statsguru or Howstat — at aggregate level.
- Cricsheet withholds some matches by policy. Each archive's
README.txtsays so explicitly. In this snapshot, the men's Test, ODI and T20I archives state that matches featuring the Afghanistan men's team (or played in the Afghanistan Premier League) have been withheld, under a Cricsheet policy linked from the README. We count exactly what's missing in §2.8.
⚠️ Common pitfall: scraping instead of downloading. It is tempting to write a script that pulls thousands of pages from a statistics website. Before you do, read the site's terms of use; many forbid automated scraping, and heavy scraping can hurt a free service other fans rely on. Cricsheet gives you the files on purpose. Use the download, and use web databases the way they are meant to be used: one query at a time, to check a number.
Why "ball by ball" changes everything
A scorecard is a summary that someone else chose. Ball-by-ball data is the raw material from which any summary can be built — including ones nobody has thought of yet. Chapter 1 argued that cricket's traditional statistics hide more than they reveal (Chapter 1); ball-by-ball data is what lets us build the replacements: phase strike rates (Chapter 8), expected runs from a match state (Chapter 19), win probability (Chapter 20). None of those can be computed from a career average.
2.2 Setting up your toolkit
The cricket question: what does Nusrat — a statistics student in Dhaka with a five-year-old laptop and an unreliable connection — need installed to run every line of code in this book?
The answer is: Python, a handful of free libraries, and about 140 MB of disk for the data (roughly 90 MB of Cricsheet zips plus a 48 MB Parquet cache). Nothing in this book needs a paid tool, a GPU, or a cloud account.
Installing Python
You have two good routes.
Route 1 — python.org and pip (lighter; what this book's code was run with).
- Windows: download the installer from python.org. On the first screen of the installer, tick
"Add python.exe to PATH" before you click Install — forgetting this is the single most common
reason
python"isn't recognised" afterwards. Open a new terminal (PowerShell or Command Prompt) and typepython --version. - macOS: download the macOS installer from python.org (or, if you already use Homebrew,
brew install python). In Terminal, the command is usuallypython3, notpython. - Linux: Python 3 is almost certainly installed already (
python3 --version). You may need your distribution'spython3-venvandpython3-pippackages.
Then create a virtual environment — a private folder of libraries for this project, so that installing something for cricket never breaks something else on your machine:
python -m venv .venv
# Windows: .venv\Scripts\activate
# macOS/Linux: source .venv/bin/activate
pip install pandas pyarrow numpy matplotlib seaborn scipy statsmodels scikit-learn xgboost plotly networkx lifelines jupyter
pyarrow is the one people forget: it is the engine pandas uses to read and write the Parquet files
our cache is built on (§2.6).
Route 2 — Anaconda or Miniconda (heavier; friendlier on locked-down machines). Anaconda is a
distribution that bundles Python with hundreds of scientific libraries and its own package manager,
conda. It is a large download — if your connection is slow, prefer Miniconda (just Python and
conda) and install only what you need: conda install pandas pyarrow matplotlib seaborn scipy
statsmodels scikit-learn and the rest with pip or conda as needed. Conda is a good choice on a
university computer where you cannot install system software, because everything lives in your user
folder.
Both routes give you the same libraries. Pick one and don't mix them in the same environment.
Jupyter or scripts?
A Jupyter notebook is a document of code cells and their outputs, run interactively in a browser.
A script is a plain .py file you run from top to bottom with python code/01_raw_json.py.
Notebooks are wonderful for exploration — you load the IPL once and poke at it for an hour. Scripts are better for anything you want to trust later, because they always run in order from a clean start.
⚠️ Common pitfall: the notebook that only works on your machine. In a notebook you can run cell 7, then cell 3, then edit cell 5 — and end up with variables that no longer match the code on screen (analysts call it hidden state). Before you share a number from a notebook, use "Restart kernel and run all". Every number in this book comes from a script run top to bottom, which is why you can reproduce it.
This book's chapter code is scripts, each with the same header so it can find the toolkit wherever you put the book folder:
import sys
from pathlib import Path
BOOK = Path(__file__).resolve().parents[3] # .../cricket-analytics
sys.path.insert(0, str(BOOK / "toolkit"))
sys.path.insert(0, str(BOOK / "project"))
import matplotlib
matplotlib.use("Agg")
from cricdata import load_deliveries, load_matches, batting_summary, bowling_summary
Line by line: Path(__file__).resolve() is the full path of the script itself; .parents[3] climbs
three folders up from code/ to the book's root (code → chapter → part → book). sys.path is the
list of folders Python searches when you import something; inserting toolkit/ at the front means
import cricdata finds the book's toolkit. matplotlib.use("Agg") tells the plotting library to draw
into files rather than open windows — so the scripts run the same on a laptop, a server, or a machine
with no screen. You will copy this header into every script you write for the rest of the book.
The folder layout you are working in:
cricket-analytics/
├── toolkit/ cricdata.py, venues.py, tracking_sim.py (the shared data layer)
├── data/
│ ├── raw/ Cricsheet zips + people.csv (downloaded once)
│ ├── processed/ <code>_deliveries.parquet, <code>_matches.parquet (the cache)
│ └── reference/ sourced tables (IPL auction prices, ...)
├── project/crease/ the analytics platform you build, one module per chapter
└── part-01-foundations/chapter-02-cricket-data-sources/code/ this chapter's scripts
🔄 Check your understanding
- Why does the book insist on a virtual environment rather than installing libraries "globally"?
- A friend runs
pd.read_parquet("ipl_deliveries.parquet")and gets an error about a missing engine. What did they forget to install?- Statsguru and Cricsheet both "have" Virat Kohli's IPL career. Name one question only one of them can answer.
Answer
- So that this project's library versions can't break (or be broken by) other projects on the same machine, and so the setup is reproducible: anyone can recreate the same environment.
pyarrow(or another Parquet engine such asfastparquet). pandas reads Parquet through it.- Anything that needs individual deliveries — e.g. Kohli's strike rate in overs 16–20, or his record against a particular bowler ball by ball — needs Cricsheet. Statsguru, in turn, covers long histories (pre-2001 Tests) that Cricsheet does not.
2.3 Anatomy of a Cricsheet match file
The cricket question: what exactly is in the file — and what does a single delivery look like before anyone touches it?
Open the IPL archive with nothing but Python's standard library (code/01_raw_json.py):
import json, zipfile
zf = zipfile.ZipFile(BOOK / "data" / "raw" / "ipl_json.zip")
names = zf.namelist()
match = json.load(zf.open("1535465.json")) # the IPL 2026 final
print(list(match.keys()))
print(match["meta"])
Archive: ipl_json.zip (5.2 MB)
Files in archive: 1245 (JSON match files: 1243; others: ['README.txt', 'LICENSE.txt'])
Top-level keys: ['meta', 'info', 'innings']
meta: {'data_version': '1.3.0', 'created': '2026-06-01', 'revision': 2}
Nineteen IPL seasons — every match from April 2008 to the 2026 final — fit in 5.2 MB compressed. Each
match is one JSON file named by its match id (1535465) — for most matches the same number
ESPNcricinfo uses for that match, which makes cross-checking easy. JSON (JavaScript Object Notation) is a text format for nested data:
curly braces {} hold named fields (Python reads them as a dict), square brackets [] hold ordered
lists (Python lists).
A match file has three top-level parts:
meta— about the file: the format version (1.3.0), when it was created, and its revision number. Revision 2 means Cricsheet has corrected this match once since first publishing it — data is not frozen, and that matters for caching (§2.6).info— about the match: who, where, when, toss, result.innings— the ball-by-ball record.
info keys: ['balls_per_over', 'city', 'dates', 'event', 'gender', 'match_type', 'officials', 'outcome', 'overs', 'player_of_match', 'players', 'registry', 'season', 'team_type', 'teams', 'toss', 'venue']
info['dates'] = ['2026-05-31']
info['event'] = {'name': 'Indian Premier League', 'stage': 'Final'}
info['venue'] = Narendra Modi Stadium, Ahmedabad
info['teams'] = ['Gujarat Titans', 'Royal Challengers Bengaluru']
info['toss'] = {'decision': 'field', 'winner': 'Royal Challengers Bengaluru'}
info['outcome'] = {'winner': 'Royal Challengers Bengaluru', 'by': {'wickets': 5}}
info['overs'] = 20
info['player_of_match'] = ['V Kohli']
info['season'] = 2026
Players listed per team: {'Gujarat Titans': 12, 'Royal Challengers Bengaluru': 12}
Registry entries (players + officials): 29; e.g. 'V Kohli' -> ba607b88
Notice three things. dates is a list, because a Test has five of them. players lists twelve
names per side — consistent with the IPL's Impact Player rule, under which a substitute can come in to
bat or bowl. And registry maps every person named in the file (24 players plus 5 officials) to an
eight-character identifier such as ba607b88. Remember that identifier: the toolkit copies it
onto every delivery, and in §2.9 it rescues us.
The hierarchy: match → innings → over → delivery
Innings 1: team='Gujarat Titans', overs=20, deliveries=124, keys=['team', 'overs', 'powerplays'], target=None
Innings 2: team='Royal Challengers Bengaluru', overs=18, deliveries=109, keys=['team', 'overs', 'powerplays', 'target'], target={'overs': 20, 'runs': 156}
The cricket data model is a tree. A match has innings; an innings has overs; an over has
deliveries; a delivery has an outcome. Gujarat Titans' innings has 20 overs but 124 deliveries —
four more than the 120 legal balls of a full T20 innings, because of wides and no-balls. The chase
has a target (156 off 20 overs) that the first innings doesn't. Here is one delivery from the
first over — the wide that carried a review:
{
"actual_delivery": "0.5",
"batter": "B Sai Sudharsan",
"bowler": "JA Duffy",
"extras": {
"wides": 1
},
"non_striker": "Shubman Gill",
"review": {
"by": "Gujarat Titans",
"umpire": "Nitin Menon",
"batter": "B Sai Sudharsan",
"decision": "upheld",
"type": "wicket"
},
"runs": {
"batter": 0,
"extras": 1,
"total": 1
}
}
and the first wicket of the final, Shubman Gill caught off Josh Hazlewood in the third over:
{
"actual_delivery": "2.2",
"batter": "Shubman Gill",
"bowler": "JR Hazlewood",
"non_striker": "B Sai Sudharsan",
"runs": {
"batter": 0,
"extras": 0,
"total": 0
},
"wickets": [
{
"player_out": "Shubman Gill",
"fielders": [
{
"name": "RM Patidar"
}
],
"kind": "caught"
}
]
}
Every delivery has batter, bowler, non_striker and a runs block with three numbers: runs
off the bat (batter), extras and the total. Everything else is optional and appears only
when it happened. wickets is a list — because, very rarely, two players can be out on one delivery
(we find the 13 such deliveries in §2.8). actual_delivery records the over-and-ball as the scorer
would say it, in the zero-based over.ball style ("0.5" is the fifth ball of the first over).
📐 Definition: delivery, legal delivery, extras. A delivery is any ball bowled — every row of the ball-by-ball table. A legal delivery is one that counts toward the over: not a wide and not a no-ball. Extras are runs not scored off the bat: wides and no-balls (charged to the bowler) and byes, leg-byes and penalty runs (not charged to the bowler). An over is six legal deliveries (five-ball sets in The Hundred), however many deliveries that takes.
How common are the optional keys? Counting every delivery in every IPL match file:
IPL deliveries in the JSON: 295,732
deliveries pct
actual_delivery 295732 100.000
batter 295732 100.000
bowler 295732 100.000
non_striker 295732 100.000
runs 295732 100.000
extras 16227 5.487
wickets 14705 4.972
review 990 0.335
replacements 585 0.198
Extras sub-keys: {'wides': 9876, 'legbyes': 4406, 'noballs': 1226, 'byes': 745, 'penalty': 2}
Rows in ipl_deliveries.parquet: 295,732 (match: True)

📊 Figure (described): Horizontal bars show the percentage of all 295,732 IPL deliveries in the JSON that carry each optional key. Extras appear on 5.49% of deliveries and wickets on 4.97%; reviews (0.34%) and replacements (0.20%) are rare. The takeaway: about one IPL delivery in twenty is an extra and about one in twenty is a wicket, and the toolkit's table must handle both — while reviews and replacements, which it does not keep, are rare enough that most analyses never miss them.
The last line of that output is the first test this book's data passes: the flattened Parquet table has exactly one row per JSON delivery. Nothing is lost or duplicated on the way in.
🔷 R corner (not run in this book's build). The same file in R, with the
jsonlitepackage:
r library(jsonlite) m <- fromJSON("1535465.json", simplifyVector = FALSE) m$info$outcome$winner length(m$innings[[1]]$overs[[1]]$deliveries) # 9 deliveries in the first over
simplifyVector = FALSEkeeps the nested lists exactly as in the JSON. Theyorkrpackage builds richer R tooling on top of Cricsheet data (its siblingcricketruses ESPNcricinfo Statsguru records); Appendix J covers R in more depth.
2.4 The toolkit, line by line (I): constants, download, phases
The cricket question: the JSON is a tree; pandas wants a table. Who decides how the tree becomes a table — and can we check their decisions?
The answer in this book is toolkit/cricdata.py, about 400 lines that every chapter imports. We will
read it in the order Python does. You do not need to memorise it. You need to have read it once, so
that when a later chapter says "balls faced excludes wides", you know where that rule lives and why.
The docstring: two warnings before any code
The file opens with a docstring — a string at the top of a module that documents it (Python shows
it when you type help(cricdata)). Most of it lists the competition codes and the phase convention we
meet below. Two paragraphs are warnings, and they are there because this chapter's own investigation
(§2.8 and §2.9) found the problems they describe:
Player identity: names are Cricsheet spellings and are NOT unique (three different "Rashid Khan"s appear
in men's T20Is). Every delivery also carries Cricsheet registry ids — batter_id, bowler_id,
non_striker_id, player_out_id. Aggregate ACROSS competitions by id, e.g. with `primary_id()` and `only_player()` below.
Coverage gap: Cricsheet withholds Afghanistan men's international matches (Tests, ODIs, T20Is) by
policy. Afghan players appear only through franchise leagues in this data.
Read a toolkit's docstring before you trust its numbers. These two paragraphs tell you that a name is
not a person and that one Test nation's men's internationals aren't in the data at all. The two
helpers the docstring points to, primary_id() and only_player(), sit at the end of the file; we use
them in §2.9.
The opening: imports and constants
from __future__ import annotations
import io
import json
import os
import urllib.request
import zipfile
from pathlib import Path
import pandas as pd
BASE_URL = "https://cricsheet.org/downloads/{code}_json.zip"
PEOPLE_URL = "https://cricsheet.org/register/people.csv"
# Default data directory: <book>/data, overridable with the CRICDATA_DIR env var.
DATA_DIR = Path(os.environ.get("CRICDATA_DIR", Path(__file__).resolve().parent.parent / "data"))
from __future__ import annotationslets the file use modern type hints such asPath | stron older Pythons. It changes nothing at run time.io,json,os,urllib.request,zipfileandpathlibare all part of Python's standard library — no installation needed. The toolkit deliberately downloads withurllibrather than a third-party library, so it has one dependency: pandas.BASE_URLis a template:{code}is a hole that.format(code="ipl")fills to givehttps://cricsheet.org/downloads/ipl_json.zip. Every Cricsheet archive follows that pattern, which is why one function can fetch all twenty competitions.DATA_DIRsays where data lives.os.environ.get("CRICDATA_DIR", default)reads an environment variable if you've set one and otherwise uses<book>/data. That one line is how you'd point the toolkit at a bigger external drive without editing it.
Then a dictionary of the twenty competition codes the book uses:
COMPETITIONS = {
"tests_male": "Men's Test matches",
"odis_male": "Men's One-Day Internationals",
"t20s_male": "Men's T20 Internationals",
"t20s_female": "Women's T20 Internationals",
"it20s_male": "Men's non-official international T20s",
"odis_female": "Women's One-Day Internationals",
"ipl": "Indian Premier League",
...
"wpl": "Women's Premier League",
"wbb": "Women's Big Bash League",
}
A Python dict maps keys to values. The keys are Cricsheet's own archive names, so the code you
type ("ipl", "wbb") is exactly the name in the download URL.
download(): fetch once, never again
def download(code: str, data_dir: Path | str = DATA_DIR, force: bool = False) -> Path:
"""Download one Cricsheet archive to data_dir/raw/<code>_json.zip."""
raw = Path(data_dir) / "raw"
raw.mkdir(parents=True, exist_ok=True)
dest = raw / f"{code}_json.zip"
if dest.exists() and not force:
return dest
url = BASE_URL.format(code=code)
req = urllib.request.Request(url, headers={"User-Agent": "cricket-analytics-textbook/1.0"})
with urllib.request.urlopen(req, timeout=120) as resp, open(dest, "wb") as fh:
fh.write(resp.read())
return dest
Path(data_dir) / "raw"— the/operator on aPathjoins folder names, and works identically on Windows (\) and macOS/Linux (/).mkdir(parents=True, exist_ok=True)creates the folder and any missing parents, and doesn't complain if it already exists.f"{code}_json.zip"is an f-string: thefprefix lets you put Python expressions inside{}.- The key line:
if dest.exists() and not force: return dest. If the zip is already on disk, the function returns immediately. On a slow connection this is the difference between downloading 17 MB of Tests once and downloading it every time you run a script.force=Trueoverrides it when you want the latest data. - The
User-Agentheader politely identifies the client as a textbook script rather than an anonymous bot. Thetimeout=120stops a dead connection from hanging forever. with ... as resp, open(dest, "wb") as fh:opens the web response and a file for writing bytes; thewithblock closes both automatically, even if something fails halfway.
⚠️ Common pitfall: a half-written download. If your connection drops mid-download, the file on disk may be truncated — and because
dest.exists()is now true, the next run will happily skip the download and fail later with "File is not a zip file". The fix: delete the bad zip fromdata/raw/(or calldownload(code, force=True)) and run again.
_phase(): the book's phase convention, in seven lines
def _phase(match_type: str, over_number: int, ball_number: int | None = None, hundred: bool = False) -> str:
"""Phase label from a 1-based over number."""
if hundred and ball_number is not None:
return "powerplay" if ball_number <= 25 else ("middle" if ball_number <= 75 else "death")
if match_type in ("T20", "IT20"):
return "powerplay" if over_number <= 6 else ("middle" if over_number <= 15 else "death")
if match_type in ("ODI", "ODM"):
return "powerplay" if over_number <= 10 else ("middle" if over_number <= 40 else "death")
return "none"
The leading underscore in _phase is a Python convention for "internal helper — not part of the
public interface". The body is a conditional expression (a if condition else b) nested twice.
This is where three of the book's most important definitions live:
📐 Definition: phases (1-based overs). T20: powerplay overs 1–6, middle overs 7–15, death overs 16–20. ODI: powerplay 1–10, middle 11–40, death 41–50. The Hundred: balls 1–25, 26–75, 76–100 of the innings. Tests: no phases (
"none"); later chapters use innings number, overs into the innings and ball age instead.
Two things to notice. First, the T20 powerplay boundary matches the fielding restriction in the playing conditions (overs 1–6), but "middle" and "death" are analytical conventions, not laws — a death over is simply over 16 or later. Second, this function is the reason the book never conflates formats: the same over number 16 is "death" in a T20 and "middle" in an ODI. Theme 2 — three different sports — is enforced right here, in the data layer.
🔄 Check your understanding
- You set
CRICDATA_DIR=D:\cricketand calldownload("bbl"). Where does the zip go?- What does
_phase("ODI", 16)return?_phase("T20", 16)?_phase("Test", 16)?- Your laptop lost Wi-Fi halfway through downloading
odis_male_json.zip. Next morning your script fails with "File is not a zip file". Why, and what's the fix?
Answer
D:\cricket\raw\bbl_json.zip."middle","death","none".- The partial file exists, so
download()skipped re-downloading it; the truncated zip can't be opened. Delete it (or useforce=True) and download again.
2.5 The toolkit, line by line (II): parse_match() turns a tree into rows
The cricket question: when a wide is bowled, who "faced" it? When a batter runs four, is it a boundary? Which team is bowling in a super over? The answers are all in one function.
🧩 Productive struggle. Before reading on, take the nine deliveries of the final's first over (the hook) and decide, on paper: (a) what over number and ball number would you give each row? (b) How would you know, from the JSON alone, which team was bowling? (c) How would you tell a boundary four from four runs run between the wickets? Write your rules down, then compare them with the toolkit's.
The match row
parse_match(data, match_id, competition) takes one loaded JSON file and returns two things: one
dictionary describing the match, and a list of dictionaries, one per delivery.
info = data["info"]
mtype = info.get("match_type", "")
teams = info.get("teams", [None, None])
outcome = info.get("outcome", {})
by = outcome.get("by", {})
event = info.get("event", {}) or {}
toss = info.get("toss", {}) or {}
dates = info.get("dates", [])
hundred = competition == "hnd"
reg = ((info.get("registry") or {}).get("people") or {})
The pattern info.get("outcome", {}) is defensive: .get(key, default) returns the default instead
of crashing when a key is missing. Some matches have no event; abandoned matches may have no toss.
The extra or {} handles a key that exists but holds None. The last line digs two levels down —
info → registry → people — to fetch the match's name-to-identifier dictionary (§2.3), with an
empty dictionary as the fallback at each level. We'll use reg to stamp an identifier on every
delivery.
Then 27 fields of match information, of which a few deserve comment:
"season": str(info.get("season")),
"start_date": pd.to_datetime(dates[0]) if dates else pd.NaT,
"n_days": len(dates),
...
"winner": outcome.get("winner"),
"result": outcome.get("result", "win" if outcome.get("winner") else None),
"win_by_runs": by.get("runs"),
"win_by_wickets": by.get("wickets"),
"win_by_innings": bool(by.get("innings")),
"method": outcome.get("method"),
"eliminator": outcome.get("eliminator"),
...
"player_of_match": "; ".join(info.get("player_of_match", []) or []),
seasonis forced to a string. Cricsheet stores some seasons as numbers (2026) and some as text ("2020/21"); a column must have one type, and only text can hold both. We'll see in §2.8 that this has consequences.start_dateis the first date;n_dayscounts dates (a five-day Test has 5).- Cricsheet only writes
resultwhen it isn't a plain win ("tie","no result","draw"). The toolkit fills in"win"when there's a winner, so you can always filter onresult. methodis"D/L"when the result came from a Duckworth–Lewis(–Stern) revision (Chapter 23).eliminatornames the winner of a tie settled by a super over — in which casewinneritself is empty, a subtlety that bites in §2.8.
The delivery rows
The heart of the toolkit is three nested for loops that walk the tree:
rows: list[dict] = []
seq = 0
for inn_idx, inn in enumerate(data.get("innings", []), start=1):
bat = inn.get("team")
bowl = [t for t in teams if t != bat]
bowl = bowl[0] if bowl else None
target = inn.get("target", {}) or {}
super_over = bool(inn.get("super_over"))
legal_in_innings = 0
for ov in inn.get("overs", []):
over_no = ov["over"] + 1 # 1-based
legal_in_over = 0
for d in ov.get("deliveries", []):
seq += 1
enumerate(..., start=1)numbers the innings 1, 2, 3, 4. Super-over innings simply continue the count: the IPL has used innings numbers 3, 4, 5 and 6 for super overs (one tie needed two of them).- Bowling team. The JSON names the batting team in each innings but not the bowling team. The
toolkit infers it: the bowling side is "whichever of the two teams isn't batting".
[t for t in teams if t != bat]is a list comprehension — a one-line loop that builds a list. This is your answer to the Productive Struggle's question (b). over_no = ov["over"] + 1. Cricsheet numbers overs from zero (the first over is over 0, as in "0.5"). The toolkit converts to the 1-based numbers commentators use, so "the 16th over" isover == 16. Every phase rule in the book depends on this one+ 1.seqis a running counter of deliveries in the match — the order in which things happened.
Inside the innermost loop, the extras and legality logic:
ex = d.get("extras", {}) or {}
runs = d["runs"]
wides = ex.get("wides", 0)
noballs = ex.get("noballs", 0)
is_legal = (wides == 0 and noballs == 0)
if is_legal:
legal_in_over += 1
legal_in_innings += 1
A delivery is legal if it is neither a wide nor a no-ball. Byes and leg-byes are legal deliveries — the ball counts, the runs just don't go to the batter. Two counters tick only on legal balls: one resets every over, one runs across the innings.
Then the row itself — 38 columns. The ones with decisions in them:
"over": over_no,
"ball_in_over": legal_in_over if is_legal else legal_in_over + 1, # ball being bowled
"legal_ball_index": legal_in_innings if is_legal else None,
"delivery_seq": seq,
"batter": d.get("batter"),
"bowler": d.get("bowler"),
"non_striker": d.get("non_striker"),
"batter_id": reg.get(d.get("batter")),
"bowler_id": reg.get(d.get("bowler")),
"non_striker_id": reg.get(d.get("non_striker")),
"player_out_id": reg.get(wk[0]["player_out"]) if wk else None,
"runs_batter": rb,
"runs_extras": runs.get("extras", 0),
"runs_total": runs.get("total", 0),
...
"is_legal": is_legal,
"is_four": rb == 4 and not non_boundary,
"is_six": rb == 6 and not non_boundary,
"is_wicket": len(wk) > 0,
"wicket_kind": wk[0]["kind"] if wk else None,
"player_out": wk[0]["player_out"] if wk else None,
"fielders": "; ".join(f.get("name", "") for f in wk[0].get("fielders", []) if f.get("name")) if wk else None,
"n_wickets_on_ball": len(wk),
"phase": _phase(mtype, over_no, legal_in_innings if is_legal else legal_in_innings + 1, hundred),
"target_runs": target.get("runs"),
ball_in_over— the answer to (a). A legal ball gets its own number; an illegal delivery gets the number of the legal ball still to come. That is why the hook's two wides both read "5".legal_ball_indexisNonefor wides and no-balls, and counts 1, 2, 3 ... across the innings for legal balls. In pandas theNonebecomesNaN, and the column becomes a float — the1.0,2.0in the hook's output.is_four/is_six— the answer to (c). Cricsheet marks runs that were not boundaries (four all-run, or overthrows that happen to total four) with anon_boundaryflag. The toolkit counts a four only when the batter got four and it wasn't flagged. In the IPL that matters 21 times in 295,732 deliveries (§2.8) — rare, but it's the difference between a correct boundary count and a nearly-correct one.- Wickets.
is_wicketis true if the list has anything in it;wicket_kind,player_outandfielderscome from the first wicket in the list (wk[0]).n_wickets_on_ballkeeps the count, so you can always find the rare cases where a second dismissal was dropped. fieldersjoins all fielder names with"; "— a caught-and-relay might credit two.- The four
_idcolumns look each name up in the match's registry:reg.get(name)returns the eight-character identifier, orNoneif the name isn't there. So every delivery carries both the friendly name (batter = "V Kohli") and the unambiguous identity (batter_id = "ba607b88"). Names are for reading; ids are for counting. §2.9 shows why that distinction matters. phase— for The Hundred, the phase is computed from the legal ball number in the innings (1–100), not the over.
That's it. Everything the book computes starts from these rows. Here is the round-trip check from
code/02_parse_and_cache.py: parse the final from the zip, and compare with the cached table:
parse_match -> 1 match row with 27 fields, 233 delivery rows with 38 columns
...
Parquet rows for this match: 233; identical to fresh parse on these columns: True
🔍 Why this works: one row per event, decisions as columns. The toolkit never drops a delivery and never merges two. Wides stay as rows, with
is_legal = False. That one choice means you can always rebuild any summary: legal balls areballs[balls.is_legal], runs conceded are computable, extras are summable. If the flattening had thrown wides away to "simplify", no later chapter could compute a bowler's economy correctly. The rule for any data pipeline: keep the atoms, add flags; don't pre-aggregate.🔄 Check your understanding
- A no-ball is bowled as the third legal ball is due, then a legal ball. What are
ball_in_overandlegal_ball_index(within the over's context) for the two rows?- A batter drives, the fielders misfield, and the batters run four. Cricsheet flags it
non_boundary. What areruns_batterandis_four?- Why does the bowling team have to be inferred?
Answer
- The no-ball row has
ball_in_over = 3andlegal_ball_index = NaN; the legal ball after it hasball_in_over = 3and a reallegal_ball_index(the innings' running count).runs_batter = 4,is_four = False. The runs count; the boundary doesn't.- Each innings in the JSON names only the batting team; the bowling team is "the other one of
info.teams".
2.6 The toolkit, line by line (III): build(), the cache, and load_*
The cricket question: the Tests archive is 899 matches and 1.7 million deliveries. Do you really have to parse 899 JSON files every time you want Joe Root's average?
No. You parse them once.
def build(code: str, data_dir: Path | str = DATA_DIR, force: bool = False) -> tuple[Path, Path]:
"""Download (if needed) and parse one archive into two Parquet files."""
data_dir = Path(data_dir)
proc = data_dir / "processed"
proc.mkdir(parents=True, exist_ok=True)
d_path, m_path = proc / f"{code}_deliveries.parquet", proc / f"{code}_matches.parquet"
if d_path.exists() and m_path.exists() and not force:
return d_path, m_path
zpath = download(code, data_dir)
matches, deliveries = [], []
with zipfile.ZipFile(zpath) as zf:
for name in zf.namelist():
if not name.endswith(".json"):
continue
with zf.open(name) as fh:
data = json.load(io.TextIOWrapper(fh, encoding="utf-8"))
m, d = parse_match(data, Path(name).stem, code)
matches.append(m)
deliveries.extend(d)
mdf = pd.DataFrame(matches).sort_values("start_date").reset_index(drop=True)
ddf = pd.DataFrame(deliveries)
ddf = ddf.merge(mdf[["match_id", "season", "start_date", "venue", "gender"]], on="match_id", how="left")
for df, path in ((mdf, m_path), (ddf, d_path)): # write-then-swap so readers never see a partial file
tmp = path.with_suffix(".tmp.parquet")
df.to_parquet(tmp, index=False)
os.replace(tmp, path)
return d_path, m_path
Read it as a recipe:
- Cache check — same pattern as
download(): if both Parquet files exist, return their paths and do nothing else. - Read straight from the zip.
zipfile.ZipFileopens the archive;zf.namelist()lists its files;README.txtandLICENSE.txtare skipped byif not name.endswith(".json"): continue. Nothing is unzipped to disk.io.TextIOWrapper(..., encoding="utf-8")decodes the bytes as UTF-8 text — important, because player names include characters beyond plain English letters. Path(name).stemturns"1535465.json"into"1535465"— the match id.matches.append(m)adds one item;deliveries.extend(d)adds every item of a list. One list ends with 1,243 match dicts, the other with 295,732 delivery dicts.pd.DataFrame(list_of_dicts)is the moment the tree becomes a table: each dict becomes a row, each key a column. A DataFrame is pandas' table — named columns, each with one data type.- The merge.
ddf.merge(mdf[[...]], on="match_id", how="left")copies four match-level columns (season,start_date,venue,gender) onto every delivery. A merge (a "join" in SQL) matches rows of two tables on a shared key.how="left"keeps every delivery even if its match were somehow missing. This is why the deliveries table has 42 columns, not 38: you can filter balls by season without touching the matches table. - Write Parquet — safely.
to_parquetsaves each table in Parquet, a compressed, column-oriented file format designed for exactly this: big tables read many times. But notice how it saves. Each table is first written to a temporary file (path.with_suffix(".tmp.parquet")turnsipl_deliveries.parquetintoipl_deliveries.tmp.parquet), and only when that file is complete doesos.replace(tmp, path)swap it into place.os.replaceis atomic on a normal disk: at every instant, the real file name points either to the complete old file or to the complete new one, never to something half-written. Why care? Writing the Tests table takes a few seconds. If another script — a second terminal, a notebook, a dashboard — reads the cache during those seconds, or your laptop's battery dies mid-write, a directto_parquet(d_path)would leave a truncated file that every later run trusts (the same trap as the half-finished download in §2.4). Write-then-swap means other readers never see a half-written file, and a crash leaves at worst a stray.tmp.parquetbeside an intact cache.
Then the two functions you'll call in every chapter:
def load_deliveries(code: str = "ipl", data_dir: Path | str = DATA_DIR) -> pd.DataFrame:
"""Ball-by-ball table for one competition (builds the cache on first use)."""
d_path, _ = build(code, data_dir)
return pd.read_parquet(d_path)
load_matches is the same with m_path. d_path, _ = ... is tuple unpacking — build returns
two paths and _ is the conventional name for "the one I don't need".
What does caching buy? code/02_parse_and_cache.py builds three archives from scratch into a
temporary folder (so the book's own cache is untouched) and times both paths. On the machine used to
build this book:
Build (JSON parse) vs cached read (Parquet):
deliveries zip_MB parquet_MB in_memory_MB build_s read_s speedup
code
wpl 20656 0.4 0.2 23.0 0.2 0.02 10.0
ipl 295732 5.2 2.4 334.0 3.1 0.13 24.0
tests_male 1730523 16.9 11.2 1970.0 15.8 0.66 24.0

📊 Figure (described): Left panel: seconds to load the WPL, IPL and men's Tests the first time (parsing JSON, orange) versus every later time (reading Parquet, blue) — 15.8 s versus 0.66 s for Tests. Right panel: megabytes on disk for the Cricsheet zip (grey) and the Parquet cache (blue); the cache is smaller than the zip for all three (11.2 MB against 16.9 MB for Tests). The takeaway: parse once, then every later load takes about a second or less.
Your timings will differ — a slower laptop might take a minute for Tests — but the ratio is the point: the cached read was 10–24 times faster here.
The column that will eat your memory
Look at the in_memory_MB column. The Tests Parquet files are 11.2 MB on disk; loaded into pandas the
deliveries table is 1,970 MB. Parquet compresses repeated text superbly — "JM Anderson" written ten thousand times
costs almost nothing on disk — but in memory pandas stores each of those strings as a separate Python
object — and the four _id columns added another few hundred megabytes of strings. On an old laptop
with 4 GB of RAM, load_deliveries("tests_male") with all 42 columns can push you into swapping.
The fix is to read only the columns you need. Parquet is columnar: each column is stored separately, so reading five of 42 columns really does read only those five:
d_path, _ = build("tests_male") # returns the paths; no re-parsing
slim = pd.read_parquet(d_path, columns=["match_id", "innings", "batter", "runs_batter", "wides"])
Tests, all 42 columns: 1,970 MB in memory (first load 0.67s, second 0.0000s — same object: True)
Tests, 5 columns: 240 MB in memory
(That output is from this chapter's Project Checkpoint, which wraps the trick in a helper.) An eight-fold saving, for one argument.
⚠️ Common pitfall: the stale cache. The cache never updates itself. If Cricsheet publishes new matches — or revises old ones, like the final's
"revision": 2— your Parquet files won't know. To refresh a competition:download(code, force=True)thenbuild(code, force=True), or from the command linepython toolkit/cricdata.py ipl --force. The book's numbers are pinned to the November 2026 snapshot precisely so that they don't drift; if you refresh, expect small differences from the printed outputs.
The file ends with a tiny command-line entry point:
if __name__ == "__main__":
import sys
force = "--force" in sys.argv # rebuild even if a cache exists
codes = [a for a in sys.argv[1:] if not a.startswith("--")] or ["ipl"]
for c in codes:
dp, mp = build(c, force=force)
print(f"{c}: {len(pd.read_parquet(mp)):,} matches, {len(pd.read_parquet(dp)):,} deliveries")
if __name__ == "__main__": runs only when you execute the file directly
(python toolkit/cricdata.py ipl wpl), not when another script imports it. It's the quickest way to
build every cache on a fresh machine before a long train journey with no Wi-Fi.
2.7 The toolkit, line by line (IV): the canonical summaries
The cricket question: "Balls faced" — does a wide count? Does a no-ball? Is a run-out at the non-striker's end an "out" for the non-striker? Every statistics site answers these questions; few write the answers down. The toolkit does.
Three small helpers
def batter_dismissed(balls: pd.DataFrame) -> pd.Series:
"""True where the *striker* was dismissed on that delivery (excludes non-striker run-outs)."""
return balls["is_wicket"] & (balls["player_out"] == balls["batter"])
BOWLER_WICKET_KINDS = {"bowled", "caught", "lbw", "stumped", "caught and bowled", "hit wicket"}
def bowler_wicket(balls: pd.DataFrame) -> pd.Series:
"""True where the dismissal is credited to the bowler (excludes run-outs etc.)."""
return balls["wicket_kind"].isin(BOWLER_WICKET_KINDS)
def runs_conceded(balls: pd.DataFrame) -> pd.Series:
"""Runs charged to the bowler: everything except byes, leg-byes and penalty runs."""
return balls["runs_total"] - balls["byes"] - balls["legbyes"] - balls["penalty"]
These introduce the most important pandas idiom of all: vectorised operations. balls["is_wicket"]
& (balls["player_out"] == balls["batter"]) doesn't loop over rows; it compares two whole columns at
once and returns a Series (one column of values) of True/False, one per delivery — a
boolean mask. balls[mask] then keeps only the rows where the mask is True. .isin(set) tests
membership for every row. On 1.7 million Test deliveries these run in milliseconds; a Python for
loop would take far longer. Chapter 3 drills this idiom
(Chapter 3).
BOWLER_WICKET_KINDS is a set (curly braces, no colons): run-outs, retired hurt and obstructing
the field aren't in it, so they are never credited to the bowler.
batting_summary()
by = [by] if isinstance(by, str) else list(by)
b = balls[~balls["super_over"]] if "super_over" in balls else balls
faced = b[b["wides"] == 0].assign(_dot=lambda d: d["runs_batter"] == 0)
g = faced.groupby(by)
out = pd.DataFrame({
"runs": g["runs_batter"].sum(),
"balls": g.size(),
"fours": g["is_four"].sum(),
"sixes": g["is_six"].sum(),
"dots": g["_dot"].sum(),
})
bylets you summarise by more than the batter:by=["batter", "phase"]orby=["batter", "season"]. The first line accepts either one name or a list. You can also group by"batter_id"instead of"batter"— one row per person even when two players share a name (§2.9).~balls["super_over"]—~means NOT. Super overs are excluded from every career number in the book, as they are from official records.faced = b[b["wides"] == 0]— balls faced excludes wides, but not no-balls. A batter can hit a no-ball for six; they faced it. A wide, by definition, was out of their reach..assign(_dot=...)adds a column;lambda d: ...is a tiny unnamed function.groupby(by)splits the table into one group per batter (or batter-and-phase), and.sum()or.size()collapses each group to one number.groupbyis to pandas what the scorer's pencil is to a scorebook: you'll use it in every chapter from here on.
Then outs and innings, the subtle part:
# The player key may be the name ("batter") or the registry id ("batter_id"); dismissals and
# non-striker appearances must be matched with the SAME key.
pkey = "batter_id" if "batter_id" in by else "batter"
out_col, ns_col = ("player_out_id", "non_striker_id") if pkey == "batter_id" else ("player_out", "non_striker")
extra = [c for c in by if c != pkey]
dis = b[b["is_wicket"] & ~b["wicket_kind"].isin(NOT_DISMISSAL)].copy()
dis[pkey] = dis[out_col]
out["outs"] = dis.groupby(by).size().reindex(out.index).fillna(0).astype(int)
keep = list(dict.fromkeys(["match_id", "innings", pkey] + extra))
keep_ns = [(ns_col if c == pkey else c) for c in keep]
inn = pd.concat([b[keep],
b[keep_ns].rename(columns={ns_col: pkey})])
out["innings"] = inn.drop_duplicates().groupby(by).size().reindex(out.index).fillna(0).astype(int)
-
pkey— which column identifies the player. Usually the name; if you grouped bybatter_id, everything below switches to the id columns (player_out_id,non_striker_id) so that outs and innings are matched to the same person the runs were. Mixing a name key with an id key would silently miscount — exactly the kind of bug a canonical function exists to prevent. -
Outs are counted by
player_out(orplayer_out_id), not bybatter. That is how a non-striker run out backing up gets their dismissal.NOT_DISMISSAL = {"retired hurt", "retired not out"}are excluded: retiring hurt is not getting out. .reindex(out.index).fillna(0)lines the outs up with the batters in the main table and fills in zero for anyone never dismissed — a batter with no outs would otherwise be missing.- Innings = distinct (match, innings) pairs in which the player appears as striker or
non-striker.
keepis the list of columns to take for the striker;keep_nsis the same list with the player key swapped for its non-striker twin.pd.concatstacks the two;drop_duplicates()removes repeats. A batter who was run out without facing a ball still batted an innings. list(dict.fromkeys([...]))is a Python idiom for "remove duplicates but keep the order" — a dict can't hold a key twice. It matters when you group byinnings:by=["innings", "batter"]would otherwise ask pandas for two columns both calledinnings, which it refuses. With the de-duplication,batting_summary(balls, by=["innings", "batting_team", "batter"])gives one line per batter per innings — Case Study 2 uses exactly that for a Test scorecard.
Finally the rate statistics, with one crucial guard:
out["average"] = (out["runs"] / out["outs"].where(out["outs"] > 0)).round(2)
out["strike_rate"] = (100 * out["runs"] / out["balls"]).round(2)
.where(out["outs"] > 0) replaces zero outs with NaN, so a batter who has never been dismissed gets
an average of NaN ("undefined"), not infinity. Chapter 4 explains why the traditional average's
treatment of not-outs is itself one of the ways statistics lie
(Chapter 4).
📐 Definition: the canonical batting table. Balls faced = deliveries as striker, excluding wides (no-balls count). Runs = runs off the bat. Outs = dismissals of that player, striker or non-striker, excluding retired hurt / retired not out. Innings = distinct (match, innings) in which the player batted. Batting average = runs / outs. Strike rate (SR) = 100 × runs / balls. Dot % = % of balls faced with no run off the bat. Boundary ball % = % of balls faced hit for 4 or 6. Boundary run % = % of runs scored in 4s and 6s. Super overs excluded.
bowling_summary()
The bowling table follows the same shape. Its definitions:
b = b.assign(_rc=runs_conceded(b), _w=bowler_wicket(b))
b = b.assign(_dot=b["is_legal"] & (b["_rc"] == 0), _bd=b["is_legal"] & (b["is_four"] | b["is_six"]))
g = b.groupby(by)
legal = b[b["is_legal"]]
gl = legal.groupby(by)
out = pd.DataFrame({
"balls": gl.size(),
"runs": g["_rc"].sum(),
"wickets": g["_w"].sum(),
...
out["overs"] = (out["balls"] // 6) + (out["balls"] % 6) / 10
out["economy"] = (6 * out["runs"] / out["balls"]).round(2)
📐 Definition: the canonical bowling table. Balls = legal deliveries bowled. Runs conceded = total runs − byes − leg-byes − penalty runs (wides and no-balls are charged to the bowler). Wickets = bowled, caught, caught and bowled, lbw, stumped, hit wicket. Economy = 6 × runs / balls. Bowling average = runs / wickets. Bowling strike rate = balls / wickets. Dot % = % of legal balls conceding nothing. Boundary % = % of legal balls hit for 4 or 6.
Note the two groupings: balls are counted on legal deliveries (gl), but runs and wickets on all
deliveries (g) — a bowler can concede runs on a wide and can take a stumping off one.
⚠️ Common pitfall:
oversis a label, not a number.(balls // 6) + (balls % 6) / 10turns 27 balls into4.3— "four overs and three balls", the way scorecards write it. It is not 4.3 overs of arithmetic: 4.3 overs is 27 balls, while 4.3 × 6 = 25.8. Never compute economy as runs / overs from this column; useballs. The toolkit's owneconomydoes.
Put it to work: the final's scorecard
With the toolkit read, scoring a match is four lines (code/02_parse_and_cache.py):
tot = final.groupby(["innings", "batting_team"]).agg(
runs=("runs_total", "sum"), wickets=("is_wicket", "sum"),
legal_balls=("is_legal", "sum"), deliveries=("runs_total", "size"))
bat = batting_summary(final, by=["batting_team", "batter"])
bowl = bowling_summary(final)
.agg(name=(column, function)) is named aggregation: several summaries in one pass, each given
a name.
Innings totals:
runs wickets legal_balls deliveries overs
innings batting_team
1 Gujarat Titans 155 8 120 124 20.0
2 Royal Challengers Bengaluru 161 5 108 109 18.0
Top scorers in the final:
runs balls fours sixes outs strike_rate
batting_team batter
Royal Challengers Bengaluru V Kohli 75 42 9 3 0 178.57
Gujarat Titans Washington Sundar 50 37 5 0 0 135.14
Royal Challengers Bengaluru VR Iyer 32 16 4 2 1 200.00
TH David 24 17 3 1 1 141.18
Gujarat Titans N Sindhu 20 18 3 0 1 111.11
JC Buttler 19 23 1 0 1 82.61
Arshad Khan 15 6 0 2 1 250.00
Bowlers with 2+ wickets in the final:
overs runs wickets economy dot_pct
bowler
Rasikh Salam 4.0 27 3 6.75 33.33
JR Hazlewood 4.0 37 2 9.25 29.17
B Kumar 4.0 29 2 7.25 45.83
Rashid Khan 4.0 25 2 6.25 37.50
Last delivery of the season: over 18, Arshad Khan to V Kohli, runs off bat 6, four=False, six=True
Extras in the final: wides=5, no-balls=0, byes=0, leg-byes=2
Two details to savour. Arshad Khan made 15 off 6 balls with the bat for Gujarat Titans, then bowled
the over in which Kohli finished the match. And the wickets column in the innings totals is a raw
count of wicket events (is_wicket) — the right number for a scorecard, but not the same as the
bowler's wickets, which exclude run-outs. Rasikh Salam's 3, Hazlewood's 2 and Bhuvneshwar Kumar's 2
account for 7 of Gujarat's 8.
🔄 Check your understanding
- A bowler's over: wide, 1, 4, no-ball (batter hits it for 4), 0, leg-bye 1, 0, 0. How many balls, and how many runs conceded, does
bowling_summaryrecord? (Assume one run for each wide and no-ball.)- The non-striker is run out backing up without facing a ball, in his only innings. What are his innings, balls, outs and average?
- Why does
batting_summaryuseplayer_outrather thanbatterto count outs?
Answer
- Legal balls: 1, 4, 0, leg-bye, 0, 0 = 6. Runs conceded: wide 1 + 1 + 4 + no-ball (1 + 4) + 0 + 0 (the leg-bye isn't charged) + 0 + 0 = 11.
- A trick question — read the code.
batting_summarybuilds its rows from balls faced (faced.groupby(by)) and then lines outs and innings up with those rows (.reindex(out.index)). A player who never faced a ball in the data you passed in has no row at all, so this dismissal is invisible in a one-match summary. Over a career it's harmless (he'll have faced balls in other innings, and the out is counted byplayer_outthere), but in a single-match scorecard he simply doesn't appear. Knowing the edges of your tools is part of the job.- Because the dismissed player isn't always the striker — the run-out non-striker must be credited with the dismissal, and the striker must not be.
2.8 What's in the snapshot — and an audit before you trust it
The cricket question: before you analyse anything, what do you actually have? And where is it wrong?
The inventory
code/03_snapshot_inventory.py loops over all twenty competitions. To count deliveries it reads only
the match_id column of each Parquet file — the column trick from §2.6 — so the whole inventory runs
in seconds:
competition matches deliveries first last match_types gender
code
tests_male Men's Test matches 899 1730523 2001-12-19 2026-10-28 Test male
odis_male Men's One-Day Internationals 2617 1388641 2002-06-27 2026-11-02 ODI male
t20s_male Men's T20 Internationals 3649 820658 2005-02-17 2026-11-01 T20 male
t20s_female Women's T20 Internationals 2200 499978 2009-06-18 2026-10-25 T20 female
it20s_male Men's non-official international T20s 240 52749 2010-06-04 2024-05-26 IT20 male
odis_female Women's One-Day Internationals 620 324744 2007-01-22 2026-10-28 ODI female
ipl Indian Premier League 1243 295732 2008-04-18 2026-05-31 T20 male
bbl Big Bash League 662 153250 2011-12-16 2026-01-25 T20 male
psl Pakistan Super League 357 83799 2016-02-04 2026-05-03 T20 male
cpl Caribbean Premier League 445 103717 2013-07-30 2026-09-20 T20 male
sat SA20 130 29020 2023-01-10 2026-01-25 T20 male
hnd The Hundred (men's and women's) 389 75636 2021-07-21 2026-08-16 T20 female/male
ilt International League T20 134 31407 2023-01-13 2026-01-04 T20 male
mlc Major League Cricket 109 25529 2023-07-13 2026-07-18 T20 male
bpl Bangladesh Premier League 469 111232 2012-02-11 2026-01-23 T20 male
lpl Lanka Premier League 143 32917 2020-11-26 2026-08-08 T20 male
ntb Vitality T20 Blast 1570 360545 2014-05-16 2026-07-18 T20 male
sma Syed Mushtaq Ali Trophy 695 158839 2016-01-02 2024-12-15 T20 male
wpl Women's Premier League 88 20656 2023-03-04 2026-02-05 T20 female
wbb Women's Big Bash League 527 120569 2015-12-18 2026-11-02 T20 female
Matches withheld by Cricsheet, per each archive's README: {'tests_male': 14, 'odis_male': 162, 't20s_male': 166, 'it20s_male': 10}
tests_male README: A further 14 matches have been withheld due to either featuring the Afghanistan men's team or being played in the Afghanistan Premier League, due to the Cricsheet policy to no longer feature matches involving Afghanistan men or played in Afghanistan Premier League (see https://cricsheet.org/withheld-matches for more information
TOTAL: 17,186 matches, 6,420,141 deliveries across 20 competitions
T20 internationals per year (men, women):
year 2016 2017 2018 2019 2020 2021
t20s_male 82 53 74 206 72 289
t20s_female 36 10 113 141 49 101
Six and a half million deliveries, free. A few things a careful analyst notices in that table:
- The Hundred is typed
T20in Cricsheet (itsmatch_type), and holds men's and women's matches in one archive. Always filter ongenderbefore you analyse it — and remember that its "overs" are five-ball sets: every Hundred match hasballs_per_over = 5, twenty sets per innings. - The Syed Mushtaq Ali Trophy stops in December 2024 in this snapshot; the non-official men's
internationals (
it20s_male) stop in May 2024. Coverage of a competition can lapse; don't assume "the latest season" exists for every code. - Afghanistan men's internationals are not in the data. Cricsheet withholds 14 Tests, 162 ODIs, 166 T20Is and 10 non-official T20s by policy. Afghan players still appear in franchise leagues — Rashid Khan took 21 wickets for Gujarat Titans in IPL 2026 (§2.11) — but any international analysis of Afghanistan, or any "all T20Is" baseline, is missing those matches. Say so whenever it matters.

📊 Figure (described): A grid with the twenty competition codes as rows and calendar years 2002–2026 as columns; each cell's colour shows matches that year on a log scale (blank = none). Men's Tests and ODIs run across the whole period; men's T20Is grow from a handful in 2005 to over 500 a year by 2024–2026; women's T20Is jump from 10 in 2017 to 113 in 2018 and reach 415 in 2025; the franchise leagues appear as solid bands from their founding years (IPL 2008, BBL 2011, PSL 2016, SA20/ILT20/MLC 2023). The takeaway: the data is overwhelmingly modern and T20-heavy — a fact that shapes what any "all cricket" statistic really measures.
How big is "a match" in each format? Counting legal balls per match (super overs excluded):
Per-match volume by format (super overs excluded):
matches median_deliveries median_legal_balls max_legal_balls mean_wides mean_noballs
format
Test (men) 899 1966.0 1949.0 2699 4.45 12.07
ODI (men) 2617 571.0 557.0 601 12.24 2.03
T20I (men) 3649 240.0 231.0 241 8.72 1.01
The Hundred 389 203.0 196.0 201 5.87 1.16

📊 Figure (described): Four violin shapes show the distribution of legal deliveries per match on a log scale: Tests centre near 1,949, ODIs near 557, T20Is near 231 and The Hundred near 196, each with a long thin tail down to rain-ruined matches with almost no play. The takeaway: a Test is about eight T20s of data, and every format has a tail of shortened matches you must decide how to handle.
Theme 2 in four rows. A median Test gives you about 1,949 legal balls of evidence; a median T20I, 231. A Test match averages 12.07 no-ball deliveries against about one in a T20I — mostly because a Test has about eight times as many overs, though the rate per over is also higher (roughly 12.07 / 325 ≈ 0.037 against 1.01 / 38.5 ≈ 0.026, using the median match lengths). ODIs have the most wide deliveries per match (12.24), though per over T20Is have more (8.72 in at most 40 overs). Different sports, different data.
And two numbers in that table should make you sit up: a T20I with 241 legal balls and an ODI with 601. A 20-over match has at most 240 legal balls; a 50-over match, 600. Something's off — which brings us to the audit.
The audit
code/04_data_quality.py runs the checks you should run on any new cricket dataset. Here's what it
finds in the IPL.
1. Season labels are strings, not years.
IPL season labels as Cricsheet stores them:
matches first_match last_match
season
2007/08 58 2008-04-18 2008-06-01
2009 57 2009-04-18 2009-05-24
2009/10 60 2010-03-12 2010-04-25
2011 73 2011-04-08 2011-05-28
...
2020/21 60 2020-09-19 2020-11-10
2021 60 2021-04-09 2021-10-15
...
2026 74 2026-03-28 2026-05-31
dtype of season column: object
The first IPL, played April–June 2008, is labelled "2007/08". IPL 2010 is "2009/10". The 2020
season, played September–November 2020 in the UAE, is "2020/21". If you filter
balls[balls.season == "2008"] you get nothing, silently. The labels follow the cricket
calendar of the time, not the tournament's own name. (dtype: object is pandas' way of saying
"text".) The same thing happens in the WPL, whose 2026 season is labelled "2025/26". Crease's data
module (Project Checkpoint) adds an integer year to fix this once.
2. Results, ties and super overs.
IPL results: {'win': 1218, 'tie': 16, 'no result': 9}
IPL method: {None: 1220, 'D/L': 23}
IPL ties decided by an eliminator (super over): 16
Super-over deliveries: 175 in 16 matches (innings numbers used: [np.int64(3), np.int64(4), np.int64(5), np.int64(6)])
Sixteen IPL ties, all settled by super overs — which means sixteen matches where winner is empty
and the side that went through is in eliminator. Twenty-three results came by D/L. Any "win %"
calculation must decide what to do with both, and must say which it chose.
3. Over lengths.
Legal balls in non-final overs (IPL): {5: 4, 6: 45268, 7: 4}
match_id innings over legal is_last season team1 team2
1136564 2 12 7 False 2018 Rajasthan Royals Sunrisers Hyderabad
335987 1 8 5 False 2007/08 Rajasthan Royals Kings XI Punjab
335994 2 11 7 False 2007/08 Mumbai Indians Deccan Chargers
336015 2 15 5 False 2007/08 Rajasthan Royals Delhi Daredevils
392198 2 11 7 False 2009 Delhi Daredevils Rajasthan Royals
419155 1 19 7 False 2009/10 Chennai Super Kings Delhi Daredevils
501202 1 6 5 False 2011 Pune Warriors Kings XI Punjab
501255 2 10 5 False 2011 Royal Challengers Bangalore Kolkata Knight Riders
Of 45,276 completed IPL overs, eight had the wrong number of legal balls: four with five, four with seven. Umpires miscount; the over as bowled is what happened, and the scorer records it. This is also why a T20I can have 241 legal balls. The data is right — the match was unusual.
🏏 Eye test: Wendell Baptiste, who bowled first-class overs for fifteen years, laughed when Nusrat showed him the seven-ball overs. "You think that's rare? Ask any bowler. The umpire's got six pebbles in his pocket and a lot on his mind." Then he got serious. "But watch what your code assumes. If you work out 'balls remaining' as 120 minus six times the over number, those eight overs break your sums." He's right, and it's a lesson the data alone wouldn't flag: a model that assumes the Laws were followed perfectly will be wrong in exactly the moments a scorer would remember. Count legal balls; don't infer them from over numbers.
4. What the flattening simplifies.
Deliveries with 2 wickets recorded on them: 0 (the toolkit keeps only the first in wicket_kind/player_out)
Deliveries with 4 off the bat that are NOT boundaries (run, or overthrows): 21
Penalty runs in the whole IPL: 10
Retired hurt / retired not out: 19 {'retired hurt': 19}
...
Deliveries carrying two wickets, all 20 competitions: 13 {'tests_male': 1, 'odis_male': 2, 't20s_male': 5, 't20s_female': 2, 'bbl': 1, 'bpl': 1, 'sma': 1}
The toolkit's one delivery-level simplification — keeping only the first wicket on a delivery — affects 13
deliveries in 6.4 million, none of them in the IPL. That's an acceptable trade for a simple table,
and because n_wickets_on_ball records it, you can always find them. That is what a well-designed
simplification looks like: rare, documented, and recoverable.
5. Missing values.
Missing values in the matches table:
match_number 74
stage 1169
city 51
winner 25
win_by_runs 685
win_by_wickets 583
method 1220
eliminator 1227
Most of these are structurally missing, not errors: stage is empty for league matches (only
playoffs have one), win_by_runs is empty when a side won by wickets, winner is empty for the 16
ties and 9 no-results (16 + 9 = 25). But city is missing for 51 IPL matches — a genuine gap. The
venue name is still there, which is why toolkit/venues.py maps venues as well as cities to host
countries.
⚠️ Common pitfall:
dropna()without thinking. pandas'dropna()removes every row with a missing value in any column. On the IPL matches table it would delete every match with nostage— 1,169 of 1,243 — leaving you with the playoffs. Missing is not the same as wrong. Ask why a value is missing before you drop it.
Extras through time
Extras are small but they are the cleanest signal of how umpiring and bowling interpret the Laws. Runs per match, by IPL season:
Extras runs per match by IPL year:
wides noballs legbyes byes
year
2008 10.28 1.41 6.41 1.26
...
2019 7.55 0.98 3.92 1.33
...
2022 11.64 0.97 4.42 1.12
2023 10.00 1.35 4.47 1.20
2024 11.99 1.06 4.30 1.17
2025 11.05 0.93 3.80 0.66
2026 12.31 0.85 3.26 1.14

📊 Figure (described): Four lines track extras runs per IPL match from 2008 to 2026. Wides (blue) fall from 10.28 in 2008 to a low of 7.55 in 2019, then jump to 11.64 in 2022 and reach 12.31 in 2026. Leg-byes (orange) fall steadily from 6.41 to 3.26. No-balls and byes stay near one run per match. The takeaway: wides have risen by roughly four runs a match since 2019, while leg-byes have halved since 2008.
Why? The data can't tell you. Candidates a cricket person would raise include changes in how wides are called and reviewed, bowlers attempting wider lines to batters who move around the crease, and more batters getting bat on ball (fewer leg-byes). Each is a hypothesis to test, not a conclusion — and that distinction is the habit this book is trying to build.
How batters get out, format by format
Dismissal mix (% of dismissals; caught includes c&b):
wicket_kind caught bowled lbw run out stumped other
Tests (men) 61.4 17.5 16.6 2.6 1.8 0.1
ODIs (men) 60.4 18.8 11.1 7.2 2.4 0.1
T20Is (men) 59.5 21.6 7.8 7.9 3.0 0.2
ODIs (women) 53.1 20.9 13.0 8.8 4.2 0.1
T20Is (women) 43.4 27.0 10.1 14.2 5.0 0.2
IPL 66.3 16.7 6.0 8.1 2.6 0.2

📊 Figure (described): Six stacked bars split all dismissals into caught, bowled, lbw, run out, stumped and other, for men's Tests, ODIs and T20Is, women's ODIs and T20Is, and the IPL. Caught dominates everywhere but ranges from 66% in the IPL to 43% in women's T20Is; lbw falls from 17% in Tests to 6% in the IPL; run-outs rise from 3% in Tests to 14% in women's T20Is. The takeaway: the way wickets fall is itself a fingerprint of the format.
Read it as a cricketer. Lbw is a Test dismissal (16.6%) — balls hitting the pad from batters defending on length — and nearly vanishes in the IPL (6.0%), where batters are moving and swinging. Run-outs are a white-ball dismissal (2.6% in Tests, 8.1% in the IPL), because white-ball batters run risks. And women's T20Is stand apart: only 43.4% caught, 27.0% bowled and 14.2% run out — more than five times the Test rate. Is that about women's cricket, or about the much wider range of standards in women's T20Is (which now include many associate nations)? You can't tell from one table; Chapter 26 compares women's leagues with internationals properly (Chapter 26). Theme 2 again: never pool these into one "dismissal rate".
🔄 Check your understanding
- You want every IPL 2010 delivery. Why does
balls[balls.season == "2010"]return an empty table, and what should you filter on?- Your T20 model computes "balls remaining" as
120 - 6 * (over - 1) - ball_in_over. Name two things in this section that break it.- Of the 25 IPL matches with no
winner, how many are genuinely missing data?
Answer
- Cricsheet labels IPL 2010 as
"2009/10". Filter on that label, or add an integer year fromstart_date(Crease'sadd_season_year) and filter onyear == 2010.- Overs with five or seven legal balls; and
ball_in_overon wides/no-balls (which repeats the upcoming ball's number). Count legal balls withlegal_ball_indexinstead. (D/L-shortened innings also break the 120.)- None. All 25 are ties (16) or no-results (9);
winneris empty by design.
2.9 Names are not identities: the people register
The cricket question: is "Rashid Khan" in men's T20Is the Afghan leg-spinner? (Read §2.8 again before you answer.)
The delivery tables show names — the short form Cricsheet uses on scorecards, like V Kohli or
S Mandhana. Names are friendly but not unique. Cricsheet solves this with a people register: a
table with one row per person, an eight-character identifier, and links to other databases. Each
match file's registry block (§2.3) uses the same identifiers, and parse_match() copies them onto
every delivery as batter_id, bowler_id, non_striker_id and player_out_id (§2.5). The toolkit
loads the register itself with load_people():
def load_people(data_dir: Path | str = DATA_DIR) -> pd.DataFrame:
"""Cricsheet people register (maps names to identifiers incl. ESPNcricinfo ids)."""
dest = Path(data_dir) / "raw" / "people.csv"
if not dest.exists():
dest.parent.mkdir(parents=True, exist_ok=True)
req = urllib.request.Request(PEOPLE_URL, headers={"User-Agent": "cricket-analytics-textbook/1.0"})
with urllib.request.urlopen(req, timeout=120) as resp, open(dest, "wb") as fh:
fh.write(resp.read())
return pd.read_csv(dest)
Same pattern as before: download once, then read. code/05_people_register.py:
People register: 18,698 people, 22 columns
People with each external key (top 8):
key_cricinfo 18653
key_cricketarchive 4508
key_pulse 2010
key_bcci 1321
key_nvplay 1142
key_bigbash 296
key_cricingif 130
key_cricketworld 127
A few rows:
identifier name unique_name key_cricinfo key_cricketarchive
be150fc8 EA Perry EA Perry 275487.0 187173.0
a94e08ea Mushfiqur Rahim Mushfiqur Rahim 56029.0 66741.0
ed840f44 Nida Dar Nida Dar 333355.0 161704.0
7dc35884 Shakib Al Hasan Shakib Al Hasan 56143.0 73152.0
5d2eda89 S Mandhana S Mandhana 597806.0 384151.0
ba607b88 V Kohli V Kohli 253802.0 101095.0
key_cricinfo is the player's ESPNcricinfo id — the number at the end of the player's profile
address on that site. Almost everyone in the register (18,653 of 18,698) has one, which makes the
register the bridge between Cricsheet's ball-by-ball data and Statsguru's long history. When your
computed number differs from a published one, the ESPNcricinfo id lets you check you're even looking
at the same person.
Same name, different player
Display names shared by 2+ people in the register: 275 (covering 592 people)
name
Imran Khan 6
Rashid Khan 5
Abdul Rahman 4
...
Everyone in the register called 'Rashid Khan':
identifier name unique_name key_cricinfo key_cricketarchive
3f811de0 Rashid Khan Mohammad Rashid Ali Khan 270117.0 NaN
5f547c8b Rashid Khan Rashid Khan 793463.0 1738090.0
69cccff3 Rashid Khan Rashid Khan (2) 1161020.0 NaN
700e1c72 Rashid Khan Rashid Khan (3) 42421.0 1669.0
1eaac48d Rashid Khan Rashid Khan (4) 1498680.0 NaN
Five different people share the display name "Rashid Khan". The register tells them apart with
unique_name and identifier. The real question is whether collisions like this reach the data you
analyse. The script answers it twice: first from the team sheets (every player listed in every match
file's registry), then from the delivery tables themselves, pairing each name column with its _id
column and counting names that carry more than one id (the whole thing takes about twenty seconds):
Team sheets: 11,530 player names; names used by 2+ people within one competition: 70
Delivery tables: 11,301 player names, 0 rows without an id
Names that map to 2+ different players WITHIN one competition: 68
code
t20s_male 38
sma 7
bpl 7
odis_male 4
psl 3
it20s_male 2
hnd 2
t20s_female 2
ipl 1
tests_male 1
wbb 1
Names that map to 2+ different players ACROSS the whole snapshot: 127
Seventy names are shared within a competition's team sheets; 68 of them reach the ball-by-ball table (in the other two, only one of the people sharing the name ever batted, bowled or stood at the non-striker's end). Every delivery has an id for every name — not one missing.

📊 Figure (described): Horizontal bars count, for each competition, the player names that are in the ball-by-ball table used by two or more different people in that same competition. Men's T20Is lead with 38; the BPL and Syed Mushtaq Ali Trophy have 7 each; the IPL, Tests and WBBL have 1 each. The takeaway: collisions concentrate where many teams and many lightly-documented players meet — the associate- heavy men's T20I archive above all.
And here is the trap, sprung:
'Rashid Khan' in the delivery tables (bowler_id -> competitions):
1eaac48d cricinfo=1498680 ['t20s_male']
5f547c8b cricinfo=793463 ['bbl', 'bpl', 'cpl', 'hnd', 'ilt', 'ipl', 'mlc', 'ntb', 'psl', 'sat', 't20s_male']
69cccff3 cricinfo=1161020 ['t20s_male']
Men's T20Is, bowling as 'Rashid Khan' -- by name vs by bowler_id:
matches balls wickets economy
bowler
Rashid Khan 5 114 6 10.37
matches balls wickets economy
bowler_id
1eaac48d 2 48 3 10.25
5f547c8b 1 24 2 12.00
69cccff3 2 42 1 9.57
1eaac48d bowled for: ['Belgium']
5f547c8b bowled for: ['ICC World XI']
69cccff3 bowled for: ['Nepal']
bowling_summary on men's T20Is reports a "Rashid Khan" with 6 wickets in 5 matches at an economy of
10.37. That player does not exist. It is three people: a Belgian bowler, a Nepali bowler, and — in a
single ICC World XI match — the Rashid Khan who appears in ten franchise competitions in this
snapshot. His Afghanistan T20Is are among the withheld matches, so in this data his international
record is one match long. Two data facts, each harmless alone, combine into a number that is
completely wrong.
The fix was in the output all along: bowling_summary(rk, by="bowler_id") — the same function,
grouped by the id column instead of the name — splits the phantom into three real people. No extra
data, no lookup: the ids were on every row.
Pinning one person: primary_id() and only_player()
Grouping by id is perfect when you want everyone. Usually you want one named player — "Rashid Khan, the leg-spinner" — across several competitions, and you'd like the output to still say his name. The toolkit ends with two small helpers for that:
def primary_id(balls: pd.DataFrame, name: str, role: str = "batter") -> str | None:
"""The registry id that accounts for most deliveries under `name` in `role` ('batter' or 'bowler').
Use it to pin a famous name to the right person before aggregating across competitions."""
ids = balls.loc[balls[role] == name, f"{role}_id"].value_counts()
return ids.index[0] if len(ids) else None
def only_player(balls: pd.DataFrame, name: str) -> pd.DataFrame:
"""Rows involving the person most associated with `name` (as batter, non-striker, or bowler) — with the
*names* of other people who share the spelling blanked out of the way, so batting_summary /
bowling_summary on the result describe one human being."""
pid = primary_id(balls, name, "batter") or primary_id(balls, name, "bowler")
b = balls.copy()
for col in ("batter", "bowler", "non_striker", "player_out"):
clash = (b[col] == name) & (b[f"{col}_id"] != pid)
b.loc[clash, col] = name + " (other)"
return b
primary_idbuildsf"{role}_id"—"batter_id"or"bowler_id"— from the role you pass, counts the ids that appear under that name withvalue_counts()(sorted most-frequent first) and returns the top one. The famous player is, almost always, the one with the most deliveries.only_playerfinds that id (trying the batting record first, then bowling —a or breturnsbwhenaisNone), copies the table, and for each of the four name columns renames every row where the name matches but the id doesn't to"Rashid Khan (other)". Nothing is deleted. The summaries then see two different names and keep two different lines.
The script loads the eleven archives in which the famous Rashid Khan's id appears (ten franchise leagues plus men's T20Is), reading only the columns the summaries need, and compares:
Primary bowler_id for 'Rashid Khan' across these 11 archives: 5f547c8b
By name alone vs after only_player():
matches balls wickets economy
bowler
Rashid Khan 396 9079 504 6.93
matches balls wickets economy
bowler
Rashid Khan 392 8989 500 6.90
Rashid Khan (other) 4 90 4 9.93
By name alone, "Rashid Khan" has 504 wickets in 396 matches. Pinned to identifier 5f547c8b
(ESPNcricinfo id 793463), it is 500 wickets in 392 matches at an economy of 6.90 in the franchise
leagues in the data, plus that one World XI T20I — and the four matches, 90 balls and 4 wickets of the
Belgian and Nepali bowlers move to their own line. Here the error was small, because the star's
record dwarfs the others. In men's T20Is alone it was the whole answer. And notice what this figure is
not: it is not Rashid Khan's T20 career, because his Afghanistan internationals are withheld from
the data (§2.8). Say "in the franchise leagues in the data" whenever you quote an Afghan player.
The IPL is cleaner — one colliding name, Harmeet Singh, touching 586 of 295,732 deliveries
(0.20%):
IPL names shared by two different players: ['Harmeet Singh']
IPL deliveries touching a colliding name: 586 of 295,732 (0.20%)
matches balls wickets
bowler_id
2a72fd4f 27 525 26
0bf15e52 1 24 1
Two bowlers: one with 27 IPL matches, one with a single match. By name, the second one's over would quietly join the first one's record. "Cleaner" isn't "clean".
⚠️ Common pitfall: grouping by name across competitions. Concatenating several archives with
load_many()and then summarising bybattermerges everyone who shares a display name. Across this snapshot, 127 names in the delivery tables belong to two or more people. For cross-league work (Chapter 26), group by the_idcolumns, or pin the player you mean withonly_player(balls, name)before you summarise.
2.10 What Cricsheet can't tell you
The cricket question: Wendell asks: "So where in all this is the ball that seamed away from the left-hander?" Nowhere. Here is what's missing, and why it matters.
Cricsheet records what happened — who bowled, who faced, the runs, the extras, the dismissal and who took the catch. It does not record how:
| Not in Cricsheet | Why it matters | Where this book handles it |
|---|---|---|
| Line and length (where the ball pitched) | Pitch maps, "good length" bowling, what a batter struggles against | Chapter 15, with a clearly labelled simulated tracking layer |
| Ball speed, swing, seam, spin revolutions | Pace bowling analysis, release metrics | Described only; never invented |
| Shot direction and shot type | Wagon wheels, scoring zones, field placement | Chapter 7 and Chapter 32, simulated layer |
| Fielding positions | Field-setting strategy | Chapter 32, simulated |
| Dropped catches, misfields, runs saved | Fielding value beyond catches taken | Chapter 17, simulated or hand-charted data |
| DRS ball-tracking values | Umpiring and lbw analysis | Reviews are recorded (§2.3), the projections are not |
| Batting positions and player roles | "Openers", "finishers", "all-rounders" | Inferred from order of entry; roles from reference tables |
Ball-tracking data exists — Hawk-Eye (owned by Sony) and similar systems measure every delivery in
televised professional matches — but it is sold, not published. A franchise or board analyst may
have it; a fan in Dhaka does not. This book's response is honest and consistent: where a method needs
tracking data, we attach simulated locations to real deliveries with toolkit/tracking_sim.py
(outcomes real, locations simulated), label every such use 🧪 Simulated data, teach the method, and
explain what the real feed would change. Chapter 15 does this in full
(Chapter 15).
There's also what no dataset records: the batter's sore shoulder, the crack that opened on a length on day four, the captain's mood. Theme 5 — analytics complements, it doesn't replace — starts here, with knowing the edges of your data.
🔄 Check your understanding
- Name two analyses you can do with Cricsheet alone and two you cannot.
- Why is Afghanistan's men's international record a "data" problem and not a "cricket" problem in this book?
- Your summary of men's T20Is shows a bowler with an odd career line. What's the first thing to check?
Answer
- Can: phase strike rates; dismissal types by format; partnership runs; extras by season; win-probability tables. Cannot (without other data): pitch maps; ball-speed analysis; shot direction; dropped catches.
- The matches happened and matter; Cricsheet has withheld them by policy. Any statistic that should include them — an Afghan player's T20I record, an all-T20I baseline — is incomplete, and the book must say so rather than present it as complete.
- Whether the name maps to more than one id in that competition — summarise by
bowler_id(orbatter_id) as well as by name — and which teams the "player" appeared for.
2.11 First analysis: the leaders of IPL 2026 and WPL 2026
The cricket question: who scored the most runs and took the most wickets in IPL 2026 — and what does the data add to the bare list?
Everything is in place. code/06_first_analysis.py defines one function and calls it twice:
def season_leaders(code: str, season: str, n: int = 10):
"""Top-n batters by runs and bowlers by wickets for one season label."""
balls = load_deliveries(code)
season_balls = balls[balls["season"] == season] # boolean mask -> filtered rows
team = (season_balls.groupby("batter")["batting_team"]
.agg(lambda s: s.value_counts().index[0])) # most frequent team
bat = batting_summary(season_balls).join(team.rename("team"))
bowl_team = (season_balls.groupby("bowler")["bowling_team"]
.agg(lambda s: s.value_counts().index[0]))
bowl = bowling_summary(season_balls).join(bowl_team.rename("team"))
bowl = bowl.sort_values(["wickets", "economy"], ascending=[False, True])
return bat.head(n), bowl.head(n)
Three new idioms. .agg(lambda s: s.value_counts().index[0]) finds each player's most frequent team
(a player who changed sides mid-season would otherwise be ambiguous). .join() attaches a Series to
a table by matching index labels — here, player names. And sort_values([...], ascending=[False,
True]) sorts by wickets (most first) and breaks ties by economy (lowest first): two bowlers on 21
wickets are ordered by how cheaply they took them.
IPL 2026: 74 matches, 17,527 deliveries
IPL 2026 — most runs:
team innings runs balls outs average strike_rate fours sixes
batter
V Suryavanshi Rajasthan Royals 16 776 327 16 48.50 237.31 63 72
Shubman Gill Gujarat Titans 16 732 449 16 45.75 163.03 74 33
B Sai Sudharsan Gujarat Titans 17 722 457 16 45.12 157.99 75 30
V Kohli Royal Challengers Bengaluru 16 675 407 12 56.25 165.85 73 25
H Klaasen Sunrisers Hyderabad 15 624 390 13 48.00 160.00 48 31
Ishan Kishan Sunrisers Hyderabad 15 602 330 15 40.13 182.42 60 32
KL Rahul Delhi Capitals 14 593 340 13 45.62 174.41 56 31
Abhishek Sharma Sunrisers Hyderabad 15 563 275 14 40.21 204.73 50 43
MR Marsh Lucknow Super Giants 13 563 345 13 43.31 163.19 51 36
JC Buttler Gujarat Titans 17 526 345 14 37.57 152.46 51 26
IPL 2026 — most wickets:
team matches overs runs wickets economy average strike_rate dot_pct
bowler
K Rabada Gujarat Titans 17 64.4 626 29 9.68 21.59 13.38 44.33
B Kumar Royal Challengers Bengaluru 16 63.0 501 28 7.95 17.89 13.50 40.21
JC Archer Rajasthan Royals 16 60.0 559 25 9.32 22.36 14.40 43.89
Rashid Khan Gujarat Titans 17 56.5 516 21 9.08 24.57 16.24 34.31
A Kamboj Chennai Super Kings 14 50.2 530 21 10.53 25.24 14.38 38.74
E Malinga Sunrisers Hyderabad 15 54.2 507 20 9.33 25.35 16.30 35.89
Mohammed Siraj Gujarat Titans 17 62.0 562 19 9.06 29.58 19.58 46.24
Rasikh Salam Royal Challengers Bengaluru 12 42.5 405 19 9.46 21.32 13.53 32.68
Kartik Tyagi Kolkata Knight Riders 13 51.0 498 18 9.76 27.67 17.00 36.93
JO Holder Gujarat Titans 11 38.2 290 17 7.57 17.06 13.53 40.87

📊 Figure (described): Left: the ten leading IPL 2026 run-scorers, led by V Suryavanshi (776 at a strike rate of 237) ahead of Shubman Gill (732, SR 163) and B Sai Sudharsan (722, SR 158). Right: the ten leading wicket-takers, led by Kagiso Rabada (29 wickets, economy 9.68) and B Kumar (28, economy 7.95). The takeaway: the run list is close at the top on volume but wildly different on pace — and the wicket list hides a gap of almost two runs an over between bowlers with similar tallies.
Now read it like an analyst rather than a fan.
The top of the run list is a strike-rate story. Suryavanshi's 776 runs came off 327 balls; Gill's 732 took 449, Sai Sudharsan's 722 took 457. A gap of 120-odd balls is twenty overs of batting across a season — Suryavanshi produced more runs while using far fewer of his side's balls, leaving them for the batters after him. A list sorted by runs ranks the three 1-2-3; a list sorted by what those runs cost in balls separates them by a mile. That's Theme 1 — "traditional stats are broken" — showing up in the very first table we compute, and it's where Chapter 4 starts.
The wicket list hides economy. Rabada (29 wickets) and B Kumar (28) are almost level on wickets, but Kumar conceded 7.95 an over to Rabada's 9.68. Over a full four-over spell that's about seven runs a match. Who was more valuable? Wickets and economy pull in opposite directions; Chapter 14 puts them on one scale (Chapter 14).
Kohli's average is the highest of the ten (56.25) — because he was out only 12 times in 16 innings. A not-out-heavy average in a format where getting out costs little is precisely the average's blind spot (Chapter 4).
And the sanity check every season summary should pass — the parts must sum to the whole:
IPL 2026 sanity check: runs off the bat 26,151 + extras 1,299 = total 27,450; sixes 1,426; fours 2,332
Women's cricket: WPL 2026
The same function, with one change. The WPL season played in January–February 2026 is labelled
"2025/26" in Cricsheet:
WPL 2025/26: 22 matches, 5,250 deliveries
WPL 2025/26 — most runs:
team innings runs balls outs average strike_rate fours sixes
batter
S Mandhana Royal Challengers Bengaluru 9 377 246 7 53.86 153.25 57 9
H Kaur Mumbai Indians 8 342 227 5 68.40 150.66 36 13
NR Sciver-Brunt Mumbai Indians 7 321 212 5 64.20 151.42 48 4
L Lee Delhi Capitals 10 320 230 10 32.00 139.13 46 11
L Wolvaardt Delhi Capitals 10 317 234 7 45.29 135.47 31 8
JI Rodrigues Delhi Capitals 10 264 186 8 33.00 141.94 33 2
Shafali Verma Delhi Capitals 10 259 207 10 25.90 125.12 39 4
BL Mooney Gujarat Giants 9 258 211 8 32.25 122.27 28 2
MM Lanning UP Warriorz 8 248 198 8 31.00 125.25 37 5
A Gardner Gujarat Giants 9 244 172 9 27.11 141.86 26 8
WPL 2025/26 — most wickets:
team matches overs runs wickets economy average strike_rate dot_pct
bowler
SFM Devine Gujarat Giants 9 32.5 272 17 8.28 16.00 11.59 40.10
NSS Sharma Delhi Capitals 10 38.0 316 17 8.32 18.59 13.41 33.33
N de Klerk Royal Challengers Bengaluru 9 32.0 251 16 7.84 15.69 12.00 35.42
AC Kerr Mumbai Indians 7 28.0 210 14 7.50 15.00 12.00 38.69
N Shree Charani Delhi Capitals 10 37.4 313 14 8.31 22.36 16.14 28.32
CA Henry Delhi Capitals 8 29.0 249 14 8.59 17.79 12.43 41.95
LK Bell Royal Challengers Bengaluru 9 36.0 199 12 5.53 16.58 18.00 59.26
RS Gayakwad Gujarat Giants 7 22.0 178 11 8.09 16.18 12.00 43.94
SR Patil Royal Challengers Bengaluru 9 30.3 275 11 9.02 25.00 16.64 36.61
M Kapp Delhi Capitals 10 40.0 256 10 6.40 25.60 24.00 50.83

📊 Figure (described): Left: the WPL 2026 (Cricsheet season "2025/26") top ten run-scorers, led by Smriti Mandhana (377, SR 153), Harmanpreet Kaur (342) and Nat Sciver-Brunt (321). Right: the top ten wicket-takers, led by Sophie Devine and NSS Sharma on 17 each, with Lauren Bell's economy of 5.53 standing out. The takeaway: the same code produces the same kind of table for any competition — and the same caution about small samples applies, more so.
Look at the sample sizes. Mandhana's 377 runs came from 246 balls in nine innings; Harmanpreet's average of 68.40 rests on five dismissals. In a 22-match league every number is fragile — Theme 3, small samples, which Chapter 6 turns into a method (Chapter 6). And look at Lauren Bell: 12 wickets puts her seventh on the list, but she went at 5.53 an over with 59.26% dot balls — she conceded nothing off well over half her deliveries in a season that went at 8.54 an over (the Project Checkpoint's season table). A list sorted by wickets buries the most economical bowler in the competition.
🔄 Check your understanding
- Why does
season_leaders("wpl", "2026")return empty tables?- Rabada took one more wicket than B Kumar in IPL 2026. Using the table, roughly how many more runs did Rabada concede per four-over spell?
- Name two numbers in the WPL batting table you'd be wary of quoting without a sample size.
Answer
- The WPL's 2026 season is labelled
"2025/26". Pass that label, or filter by year with Crease'sfilter_balls(year=2026, games=...).- (9.68 − 7.95) × 4 ≈ 6.9 runs per four-over spell.
- Harmanpreet Kaur's average of 68.40 (five outs) and Nat Sciver-Brunt's 64.20 (five outs) — both rest on a handful of dismissals in a 22-match league.
📋 Try it — Evaluate this player. Vaibhav Suryavanshi's IPL 2026 line is 776 runs, 327 balls, 63 fours, 72 sixes, 16 outs. Compute (a) his boundary run % and (b) how many of his runs came from the balls he hit to the boundary versus all the others. What does that tell you about how he batted?
Answer
(a) Boundary runs = 4 × 63 + 6 × 72 = 252 + 432 = 684. Boundary run % = 684 / 776 = 88.1%. (b) 63 + 72 = 135 boundary balls produced 684 runs; the other 327 − 135 = 192 balls produced 776 − 684 = 92 runs — a strike rate of about 48 on non-boundary balls. Nearly nine-tenths of his runs came in boundaries, and 41% of the balls he faced (135 / 327) went to the rope. This is a boundary-or-nothing method at the extreme end — exactly the profile Chapter 8's boundary and dot metrics are built to describe (Chapter 8). And 327 balls is one season: whether it repeats is a projection question for Chapter 25.
📋 Try it — Analyze this match. Using
code/02_parse_and_cache.pyas a template, produce the bowling figures of Gujarat Titans in the 2026 final — the bowlers who tried to defend 155. Which Gujarat bowler was most economical among those who took two or more wickets, and which single filter do you need?
Answer
Filter to the chase,
final[final["innings"] == 2]— innings 2 is Royal Challengers Bengaluru batting, so every bowler in it is a Gujarat bowler — then callbowling_summary. From the §2.7 output, Rashid Khan bowled 4 overs for 25 runs and 2 wickets, economy 6.25: the only Gujarat bowler among the four listed with two or more wickets (Rasikh Salam, Hazlewood and B Kumar bowled for RCB). Run the filtered summary to see the rest of Gujarat's attack, including Arshad Khan's final over.
Project Checkpoint: data.py
Nusrat opens her laptop at a café near Mirpur, on a connection that drops every time a bus goes past. "Every script I've written today starts with the same six lines," she mutters, "then filters the season, then forgets the season is a string." Time to stop repeating it.
Crease, the analytics platform you build across this book, gets its first module:
project/crease/data.py. It sits directly on top of the toolkit (it never modifies it) and gives
every later chapter a small set of functions:
| Function | What it does |
|---|---|
load(code, columns=None) |
Cached ball-by-ball table; columns= reads only what you need |
load_games(code) |
Cached matches table |
clear_cache() |
Free the memory on a small machine |
season_years(games) / add_season_year(df, games) |
Integer year for Cricsheet's string season labels |
filter_balls(balls, season=, year=, phase=, innings=, team=, batter=, bowler=, gender=) |
One-call filtering; drops super overs by default |
season_table(code) |
One row per season: matches, deliveries, average first-innings total, run rate, sixes, fours, wides, wickets per match, chase win % |
snapshot_inventory(codes) / player_registry(code) |
What's in the snapshot; (match, name, identifier, team) for every player who batted or bowled, from the deliveries' _id columns |
The season fix is one line of pandas — the year of each season's first match:
def season_years(games: pd.DataFrame) -> pd.Series:
return games.groupby("season")["start_date"].min().dt.year.rename("year")
So IPL "2007/08" → 2008, "2020/21" → 2020, WPL "2025/26" → 2026. filter_balls uses it, so
year=2026 just works. The demo, code/project_checkpoint.py, runs every function:
IPL season table (only matches won outright, no D/L):
season year matches deliveries avg_first_innings run_rate sixes_per_match fours_per_match wides_per_match wickets_per_match chase_win_pct
2007/08 2008 56 13191 161.95 8.30 10.80 29.75 10.38 12.11 60.71
...
2012 2012 74 17767 157.54 7.83 9.88 25.82 8.23 11.59 54.05
...
2022 2022 74 17912 171.12 8.54 14.35 27.26 11.64 12.32 50.00
2023 2023 71 17307 182.99 8.98 15.28 29.68 10.21 12.51 45.07
2024 2024 71 17103 189.59 9.56 17.75 30.62 11.99 12.44 50.70
2025 2025 69 16463 190.94 9.68 18.13 31.30 11.51 12.09 52.17
2026 2026 71 17008 195.70 9.91 19.51 32.06 12.51 12.03 63.38
WPL season table:
season year matches deliveries avg_first_innings run_rate sixes_per_match fours_per_match wides_per_match wickets_per_match chase_win_pct
2022/23 2023 22 4999 156.59 8.08 7.23 36.41 7.77 11.77 68.18
2023/24 2024 22 5177 153.09 7.86 7.64 34.18 8.41 12.14 50.00
2024/25 2025 21 4965 162.90 8.34 8.52 37.05 9.00 12.90 66.67
2025/26 2026 22 5250 169.09 8.54 8.41 38.00 10.50 12.05 54.55
V Kohli, IPL 2026, death overs:
runs balls outs strike_rate boundary_ball_pct
batter
V Kohli 66 27 0 244.44 44.44
IPL year=2008 resolves to season label(s): ['2007/08']
season_table reproduces the book's IPL baseline — the average first-innings total rising from
157.5 in 2012 to 195.7 in 2026 — and the same function describes the WPL (156.59 in its first
season to 169.09 in its fourth) or any other competition. Notice the filter: only matches won
outright without D/L, so a rain-shortened eight-over match or a tie doesn't distort the average.
Change the filter and the numbers change: here IPL 2026 has 71 qualifying matches and 19.51 sixes a
match, while the full season had 74 matches and 1,426 sixes (§2.11), about 19.3 a match. Neither
figure is wrong; each must say what it counts.
Notice, too, the filter year=2026, batter="V Kohli", phase="death" — one line that answers a real
question: Kohli scored 66 off 27 balls in the death overs of IPL 2026 without being dismissed. Small
sample, striking number; Chapter 6 teaches you to shrink it toward something believable.
How it plugs in: Chapter 3's explore.py builds its first summaries on load and
filter_balls; Chapter 5's format profiles extend season_table across formats; Chapter 26 uses
the _id columns (via player_registry and the toolkit's only_player) to follow players across
leagues; and Chapter 39's dashboard calls
load and snapshot_inventory to populate its menus. Every chapter after this one imports
crease.data instead of rewriting these lines.
Chapter Summary
The data pipeline in one table
| Stage | Toolkit function | What it decides |
|---|---|---|
| Fetch | download(code) |
Download once to data/raw/; force=True to refresh |
| Structure | JSON meta / info / innings → overs → deliveries |
The match → innings → over → delivery tree |
| Flatten | parse_match() |
One row per delivery; 1-based overs; legality; ball_in_over vs legal_ball_index; bowling team inferred; registry ids on every name; non-boundary fours excluded; first wicket kept |
| Cache | build(code) |
Parse once to Parquet, written to a temp file and swapped in atomically; cached reads were 10–24× faster here |
| Identify | primary_id() / only_player() |
Pin a name to one person before summarising across competitions |
| Load | load_deliveries / load_matches / load_people |
Read the cache; use columns= for big archives |
| Summarise | batting_summary / bowling_summary |
The book's canonical definitions (below) |
Canonical definitions — balls faced exclude wides; outs exclude retired hurt and count non-striker run-outs; runs conceded exclude byes, leg-byes and penalties; bowler wickets exclude run-outs; super overs are excluded everywhere; phases are T20 1–6 / 7–15 / 16–20, ODI 1–10 / 11–40 / 41–50, Hundred balls 1–25 / 26–75 / 76–100, Tests none.
The audit checklist — run it on every new dataset:
- Count rows against the source (one row per JSON delivery: 295,732 = 295,732).
- Check the types of key columns —
seasonis text, not a year. - Tabulate results — ties, no-results, D/L — and decide how each is handled.
- Check over lengths and maximum balls per innings — umpires miscount.
- Ask why each missing value is missing before dropping anything.
- Read the archive's README — know what's been withheld (Afghanistan men's internationals).
- Check that names map to one person in your scope — group by the
_idcolumns or useonly_player(). - Check that parts sum to wholes (runs off the bat + extras = total).
Key numbers from this chapter
- Snapshot: 17,186 matches, 6,420,141 deliveries, 20 competitions (Cricsheet, November 2026).
- IPL: 1,243 matches, 295,732 deliveries; 5.49% carry extras, 4.97% a wicket.
- Withheld by Cricsheet: 14 Tests, 162 ODIs, 166 T20Is, 10 non-official T20s (Afghanistan men).
- Median legal balls per match: Test 1,949 · ODI 557 · T20I 231 · The Hundred 196.
- IPL 2026 leaders: Suryavanshi 776 runs (SR 237.31); Rabada 29 wickets (economy 9.68).
- WPL 2026 leaders: Mandhana 377 runs; Devine and NSS Sharma 17 wickets each.
What's Next
You have the data, the toolkit, and a first module of your own. Chapter 3 teaches the Python and
pandas behind every line you've just read — from variables to groupby and merge — and builds a
full scorecard of a real match from ball-by-ball data
(Chapter 3). Then Chapter 4 takes the leader tables you
computed here and shows how the batting average and economy rate that ranked them can mislead
(Chapter 4).