Appendix A — Python and pandas for Cricket (quick reference)

This appendix is the page you keep open beside your editor. It gathers the Python and pandas taught in Chapter 2 and Chapter 3 — plus the handful of plotting, modelling and performance patterns that later chapters lean on — into one reference, with every idiom shown on real ball-by-ball data.

It is a reference, not a course. If an idea here is new to you, the chapter that teaches it is linked from each section; read that first and come back here when you need the syntax again.

Everything on this page was run. The script appendices/code/a_python_pandas.py executes each idiom in order against the book's data snapshot (Cricsheet, through November 2026), and the output blocks below are pasted from its run (appendices/code/a_python_pandas_output.txt). Run it yourself from the book folder:

python appendices/code/a_python_pandas.py

It takes well under a minute on a laptop. Timings in the output are machine-dependent; every other number is deterministic.

Contents

§ Topic You need it for
A.1 Setup on Windows, macOS and Linux getting any code in the book to run
A.2 Core Python in one screen reading and writing small helpers
A.3 Loading data, inspecting it, and memory every chapter
A.4 Filtering "only the balls where…"
A.5 groupby every leaderboard and profile
A.6 merge joining deliveries to match results
A.7 pivot_table, crosstab, cumulative sums grids, worms, over-by-over tables
A.8 Rolling windows form lines, recent-innings strike rates
A.9 Dates and season labels the "2020/21" trap
A.10 Categories, bins, np.where / np.select ordered phases, score bands, outcome labels
A.11 Charts: matplotlib, seaborn, plotly every figure
A.12 scikit-learn: fit, predict, cross-validate Chapters 14, 20, 24 and on
A.13 Common errors and their fixes every bad afternoon
A.14 Performance old laptops, the Tests table
A.15 "I want to…" index finding the right idiom fast

The columns used below are documented one by one in Appendix B; the book's metric definitions are in Appendix C.


A.1 Setup on Windows, macOS and Linux

Full walkthrough: Chapter 2, §2.2. Everything is free; you need Python 3, about a dozen libraries, and roughly 140 MB of disk for the data (the Cricsheet zips plus a 48 MB Parquet cache).

Install Python

Route 1: python.org + pip (lighter; what this book was run with) Route 2: Miniconda / Anaconda
Windows Installer from python.org. Tick "Add python.exe to PATH" on the first screen. Test in a new PowerShell: python --version Install Miniconda for your user; use the "Anaconda Prompt"
macOS Installer from python.org, or brew install python. The command is usually python3 Miniconda installer; conda in Terminal
Linux Usually present: python3 --version. You may need your distribution's python3-venv and python3-pip packages Miniconda installer script

Create a virtual environment and install the libraries

python -m venv .venv
# Windows (PowerShell):   .venv\Scripts\Activate.ps1
# Windows (cmd):          .venv\Scripts\activate.bat
# macOS / Linux:          source .venv/bin/activate
pip install -r requirements.txt

requirements.txt in the book folder lists pandas, numpy, pyarrow, matplotlib, seaborn, scipy, statsmodels, scikit-learn, xgboost, plotly, networkx and lifelines (and streamlit, used only by the Chapter 39 dashboard). If you prefer to type it, Chapter 2's line is:

pip install pandas pyarrow numpy matplotlib seaborn scipy statsmodels scikit-learn xgboost plotly networkx lifelines jupyter

With conda: conda install pandas pyarrow matplotlib seaborn scipy statsmodels scikit-learn, then the rest with pip or conda. Pick one route per environment; don't mix them.

⚠️ Common pitfall: forgetting pyarrow. pandas reads and writes Parquet — the format of the book's data cache — through an engine library. Without pyarrow (or fastparquet), the very first load_deliveries() fails with an import error that mentions the missing engine.

The environment this appendix ran in

python 3.13.12 | stdout encoding: utf-8
  pandas     2.3.3
  numpy      2.3.5
  pyarrow    24.0.0
  matplotlib 3.10.9
  seaborn    0.13.2
  plotly     7.1.0
  scipy      1.17.0
  sklearn    1.8.0

The book's code is written to run on pandas 2.2 and later, including pandas 3 (where copy-on-write is the default — see A.13).

Running the book's scripts

Every chapter script starts 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

parents[3] climbs from code/ → chapter → part → book. Appendix scripts live one level higher (appendices/code/), so they use parents[2]. matplotlib.use("Agg") makes charts save to files instead of opening windows, so scripts run identically on a laptop, a server or a machine with no screen. Run chapter scripts from the chapter directory (python code/03_groupby_pivot.py); the header makes the working directory irrelevant for imports, but scripts write figures to the chapter's images/ folder relative to their own location.

The Windows console and UTF-8

Player names ("Sciver-Brunt", accented names in the people register), the em dashes in printed titles and the 🧪 label used for simulated data are all Unicode. On Windows, when Python's output is redirected to a file or piped to another program — and in some editors' run panes — Python encodes what it prints with the old Windows code page (cp1252), which has no 🧪 and no characters outside Western European alphabets. The script reproduces the exact failure (A.13):

emoji to a cp1252 console: UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f9ea' in position 0: character maps to <undefined>

The fix is one environment variable, PYTHONIOENCODING=utf-8, set before you run Python:

Shell For this session Permanently
PowerShell $env:PYTHONIOENCODING = "utf-8" setx PYTHONIOENCODING utf-8 (new terminals only)
cmd set PYTHONIOENCODING=utf-8 setx PYTHONIOENCODING utf-8
Git Bash export PYTHONIOENCODING=utf-8 or prefix one command: PYTHONIOENCODING=utf-8 python x.py add the export line to ~/.bashrc
macOS / Linux normally unnecessary (terminals are UTF-8) —

Two alternatives that also work: run Python in UTF-8 mode with python -X utf8 script.py (or set PYTHONUTF8=1), which additionally makes open() default to UTF-8; or put sys.stdout.reconfigure(encoding="utf-8") at the top of a script. With the variable set, the script reports stdout encoding: utf-8, as above.

Reading files has the mirror-image rule: always pass encoding="utf-8" to open() for text files (pandas' read_csv already defaults to UTF-8). A file saved with a byte-order mark at the start reads cleanly with encoding="utf-8-sig".

Notebooks or scripts?

Use Jupyter for exploring, scripts for anything you will quote. Before you trust a number from a notebook, Restart kernel and run all — cells run out of order leave hidden state. Every number in this book comes from a script run top to bottom.


A.2 Core Python in one screen

Taught in Chapter 3, §3.1–3.3.

Idea Syntax Cricket example
Variable name = value runs = 43
Types str, int, float, bool, None "V Kohli", 35, 122.86, True, "undefined"
f-string f"{x} {y:.2f}", {s:<12}, {n:>4} f"{batter} {runs} ({balls}) SR {sr:.2f}"
List [a, b, c]; x[0], x[-1], x[2:] last_over = [0, 0, 6, 4, 6, 6]
List methods / built-ins len, sum, max, min, .count(), .append() last_over.count(6)
Loop for r in over: + indented block count dots in an innings
Condition if … elif … else; == compares, = assigns if r == 0: dots += 1
Comprehension [r for r in over if r in (4, 6)] boundaries in an over
Dictionary {"runs": 43, "balls": 35}; d["runs"] one scorecard line
Function def f(a, b): … return … strike_rate(runs, balls)
Guard the impossible case return None if balls == 0 else … batter run out without facing
Tuple unpacking d_path, _ = build("ipl") ignore the value you don't need

From the script:

last_over = [0, 0, 6, 4, 6, 6]                       # IPL 2025 final, Hazlewood to Shashank Singh
line = {"batter": "V Kohli", "runs": 43, "balls": 35}

def strike_rate(runs, balls):
    """Runs per 100 balls faced; None when no balls were faced."""
    return None if balls == 0 else round(100 * runs / balls, 2)

print(sum(last_over), last_over[-1], last_over[2:], last_over.count(6), max(last_over))
print(f"{line['batter']} {line['runs']} ({line['balls']}) SR {strike_rate(line['runs'], line['balls']):.2f}")
print("boundaries:", len([r for r in last_over if r in (4, 6)]), "| zero balls ->", strike_rate(0, 0))
22 6 [6, 4, 6, 6] 3 6
V Kohli 43 (35) SR 122.86
boundaries: 4 | zero balls -> None

Positions count from 0 (last_over[0] is the first ball); slices stop before the end index (last_over[0:2] is the first two balls); indentation is syntax.


A.3 Loading data, inspecting it, and memory

The toolkit loads each competition as two tables: deliveries (one row per delivery, legal or not, 42 columns) and matches (one row per match, 27 columns). Competition codes, every column and every toolkit function are listed in Appendix B.

from cricdata import load_deliveries, load_matches
balls = load_deliveries("ipl")          # first call downloads + parses; later calls read the Parquet cache
games = load_matches("ipl")

Inspecting a table

You want Code
rows, columns balls.shape
column names balls.columns.tolist()
types balls.dtypes
first / last rows balls.head(5), balls.tail(3)
non-null counts and memory balls.info(memory_usage="deep")
distinct values and counts balls["wicket_kind"].value_counts(dropna=False)
missing values per column balls.isna().sum()
summary statistics balls[["runs_batter", "runs_total"]].describe()
one column (a Series) balls["runs_batter"]
several columns balls[["batter", "runs_batter"]] (double brackets)

Read only what you need

Parquet is a columnar format: each column is stored separately, so asking for five columns really reads only those five. pyarrow can also skip rows that fail a simple condition while reading (filters=).

PROC = BOOK / "data" / "processed"
cols = ["match_id", "season", "innings", "over", "phase", "batter", "runs_batter", "wides", "super_over"]
slim = pd.read_parquet(PROC / "ipl_deliveries.parquet", columns=cols)
only26 = pd.read_parquet(PROC / "ipl_deliveries.parquet", columns=cols,
                         filters=[("season", "==", "2026")])
tests5 = pd.read_parquet(PROC / "tests_male_deliveries.parquet",
                         columns=["match_id", "innings", "batter", "runs_batter", "wides"])
IPL deliveries: (295732, 42) | matches: (1243, 27)
all 42 columns: 333.9 MB in memory, read in 0.16 s
9 columns:      75.8 MB in memory, read in 0.04 s
9 columns, season 2026 only (filters=): 17,527 rows, 4.5 MB, 0.02 s
men's Tests, 5 columns: 1,730,523 rows, 239.8 MB
dtypes (first 10): {'match_id': 'object', 'competition': 'object', 'match_type': 'object', 'innings': 'int64', 'super_over': 'bool', 'batting_team': 'object', 'bowling_team': 'object', 'over': 'int64', 'ball_in_over': 'int64', 'legal_ball_index': 'float64'}

The memory figures that matter (measured with df.memory_usage(deep=True).sum()):

Table All 42 columns A few columns
IPL deliveries (295,732 rows) 333.9 MB 75.8 MB (9 columns); 4.5 MB for one season
Men's Test deliveries (1,730,523 rows) 1,970 MB (Chapter 2, §2.6) 239.8 MB (5 columns)

On disk the Tests deliveries file is 11.2 MB; in memory, with every text value stored as a separate Python string, it is about 2 GB. On a 4 GB laptop, never load the Tests table without columns=. Crease's data.load(code, columns=[...]) (Chapter 2) wraps the same trick with a cache.

⚠️ Common pitfall: load_many() has no columns= argument. It concatenates whole tables. For several big archives, build the list yourself: pd.concat([pd.read_parquet(PROC / f"{c}_deliveries.parquet", columns=cols) for c in codes], ignore_index=True).


A.4 Filtering

Taught in Chapter 3, §3.5. A filter is a boolean mask — a True/False Series, one value per row — used inside square brackets.

Idiom Code Note
One condition balls[balls["phase"] == "death"]
And / or / not (a) & (b), (a) \| (b), ~a brackets round each condition
Any of several values balls["season"].isin(["2024", "2025", "2026"])
A range (inclusive) balls["over"].between(7, 15)
Rows and columns balls.loc[mask, ["over", "batter", "runs_total"]]
Text contains games["team1"].str.contains("Royal Challengers") add na=False if the column has gaps
Missing / present games["method"].isna(), games["winner"].notna()
Query string b26.query("phase == 'powerplay' and wides == 0 and runs_batter == 6") readable for long conditions
Drop super overs balls[~balls["super_over"]] the book's tables always do
Balls faced balls[balls["wides"] == 0] no-balls stay in
Legal balls balls[balls["is_legal"]] no wides, no no-balls
Copy before modifying death = balls[balls["phase"] == "death"].copy() see A.13
b = balls[~balls["super_over"]]                       # the book's batting/bowling tables drop super overs
b26 = b[b["season"] == "2026"]                        # season is TEXT
death26 = b26[b26["phase"] == "death"]
jb = b[(b["bowler"] == "JJ Bumrah") & (b["phase"] == "death")]          # brackets round each condition
print(bowling_summary(jb)[["balls", "runs", "wickets", "economy"]])
recent = b[b["season"].isin(["2024", "2025", "2026"])]
last3 = b.loc[(b["match_id"] == "1535465") & (b["innings"] == 2),
              ["over", "ball_in_over", "batter", "runs_total"]].tail(3)
q = b26.query("phase == 'powerplay' and wides == 0 and runs_batter == 6")
rcb = games[games["team1"].str.contains("Royal Challengers") | games["team2"].str.contains("Royal Challengers")]
mid = b26[b26["over"].between(7, 15)]
IPL 2026 deliveries: 17523 | death: 3885
           balls  runs  wickets  economy
bowler                                  
JJ Bumrah   1423  1943      102     8.19
2024-26 deliveries (isin): 51901
        over  ball_in_over     batter  runs_total
159131    18             4  JM Sharma           1
159132    18             5    V Kohli           4
159133    18             6    V Kohli           6
IPL 2026 powerplay sixes (query): 455
RCB matches, either name (str.contains): 286
overs 7-15 via between(): 8107 == phase 'middle': 8107

The 2026 season has 17,527 deliveries in all; 17,523 once its super-over balls are dropped. The last three rows are the end of the IPL 2026 final — Kohli's four and six to win it. The str.contains line finds Royal Challengers matches under both of the franchise's names ("Bangalore" to 2023, "Bengaluru" from 2024); filtering on one exact name would miss most of its history.

⚠️ Common pitfall: a filter that returns zero rows is a bug until proved otherwise. games[games["season"] == 2026] (a number, not text) returns nothing and raises no error. Check len(result) after every important filter.


A.5 groupby

Taught in Chapter 3, §3.6. Split the rows into groups by one or more key columns, apply an aggregation to each group, combine the answers into a table indexed by the key.

Idiom Code
One number per group b26.groupby("batter")["runs_batter"].sum()
Several (named aggregation) .agg(runs=("runs_batter", "sum"), balls=("runs_batter", "size"))
Two keys .groupby(["batter", "phase"])
Keys as columns, not index .groupby([...], as_index=False)
Rows per group .size() (counts rows, including missing values)
Non-missing values per group .count()
Distinct values per group .nunique(), e.g. matches per bowler
First / last row per group .first(), .last() (after sorting)
Group result back on every row .transform("sum")
Custom aggregation ("runs", lambda s: int((s >= 200).sum()))
Add a computed column .assign(strike_rate=lambda d: 100 * d["runs"] / d["balls"])
Sort and cut .sort_values("runs", ascending=False).head(10)
faced = b26[b26["wides"] == 0]                         # balls faced exclude wides
tbl = (faced.groupby("batter")
       .agg(runs=("runs_batter", "sum"), balls=("runs_batter", "size"),
            fours=("is_four", "sum"), sixes=("is_six", "sum"))
       .assign(strike_rate=lambda d: (100 * d["runs"] / d["balls"]).round(2))
       .sort_values("runs", ascending=False))
bs = batting_summary(b26)
print("matches batting_summary:", bool((bs.loc[tbl.index[:10], "runs"] == tbl["runs"].head(10)).all()))
                 runs  balls  fours  sixes  strike_rate
batter                                                 
V Suryavanshi     776    327     63     72       237.31
Shubman Gill      732    449     74     33       163.03
B Sai Sudharsan   722    457     75     30       157.99
V Kohli           675    407     73     25       165.85
H Klaasen         624    390     48     31       160.00
matches batting_summary: True

Hand-built and toolkit numbers agree. In practice, call batting_summary(balls, by=[...]) and bowling_summary(balls, by=[...]) — they apply the book's definitions of balls, outs, runs conceded and wickets in one place (Appendix C).

transform returns a value for every original row, aligned with it — the way to put a group total beside each delivery:

team_runs = b26.groupby(["match_id", "innings"])["runs_total"].transform("sum")   # same length as b26
inn_share = (b26.assign(team_total=team_runs)
             .groupby(["match_id", "innings", "batter"], as_index=False)
             .agg(runs=("runs_batter", "sum"), team_total=("team_total", "first")))
inn_share["pct_of_total"] = (100 * inn_share["runs"] / inn_share["team_total"]).round(1)
largest share of a team total, IPL 2026:
match_id  innings    batter  runs  team_total  pct_of_total
 1529294        2  FH Allen   100         147          68.0
 1529278        1  KL Rahul   152         264          57.6
 1529267        1 Q de Kock   112         195          57.4
size vs count on wicket_kind (2026): {'death': 3885, 'middle': 8107, 'powerplay': 5531} {'death': 283, 'middle': 361, 'powerplay': 236}

The last line is the difference between size and count in one picture: size counts every delivery in each phase; count on wicket_kind counts only the rows where that column is not missing — the balls on which a wicket fell.

⚠️ Common pitfall: rates need minimums. Sort a strike-rate table without a minimum number of balls and the top is full of one-ball cameos. State a minimum (Chapter 3 uses 150 balls for an IPL season) and show the balls column next to every rate — or use the shrinkage methods of Chapter 6.


A.6 merge

Taught in Chapter 3, §3.7. A merge (a SQL "join") lines up two tables on a shared key — almost always match_id in this book.

Argument Meaning
on="match_id" the key column(s)
how="left" keep every row of the left table (the usual choice); "inner" only matched rows; "outer" everything
validate="many_to_one" raise an error if the right-hand key is not unique
indicator=True add a _merge column saying where each row was found
suffixes=("_bat", "_bowl") names for clashing columns
inns = (b.groupby(["match_id", "innings"], as_index=False)
        .agg(batting_team=("batting_team", "first"), runs=("runs_total", "sum"),
             wickets=("is_wicket", "sum"), legal_balls=("is_legal", "sum")))
merged = inns.merge(games[["match_id", "start_date", "method", "winner"]], on="match_id",
                    how="left", validate="many_to_one", indicator=True)
first = merged[(merged["innings"] == 1) & merged["method"].isna() & merged["winner"].notna()].copy()
by_year = first.groupby(first["start_date"].dt.year).agg(
    n=("runs", "size"), avg_1st=("runs", "mean"), n_200=("runs", lambda s: int((s >= 200).sum())))
dup = pd.concat([games, games.head(3)])                 # a right table whose key is NOT unique
print("rows after merging on a duplicated key:", len(inns.merge(dup[["match_id"]], on="match_id")))
games.match_id unique: True
innings rows before / after: 2480 / 2480 | _merge: {'both': 2480, 'left_only': 0, 'right_only': 0}
             n  avg_1st  n_200
start_date                    
2022        74    171.1     13
2023        71    183.0     23
2024        71    189.6     26
2025        69    190.9     32
2026        71    195.7     37
rows after merging on a duplicated key: 2486

The table reproduces the IPL's scoring surge from Chapters 1 and 3 — an average first innings of 195.7 in 2026 and 37 totals of 200 or more (matches with a winner and no D/L revision). The last line shows what a non-unique key does: three duplicated matches turned 2,480 innings into 2,486 rows, silently. validate="many_to_one" would have raised an error instead. Compare row counts before and after every merge.

🔍 Why this works: the deliveries table already carries four match columns. The toolkit copies season, start_date, venue and gender onto every delivery when it builds the cache, so many questions need no merge at all. You need merge for the result columns — winner, method, result, toss_winner — and for anything from a reference table (Appendix B, §B.5).


A.7 pivot_table, crosstab and cumulative sums

Grids

Idiom Code
Rows × columns grid of an aggregate df.pivot_table(index="batter", columns="phase", values="runs_batter", aggfunc="sum")
Count grid same with aggfunc="size"
From a two-key groupby df.groupby(["year", "phase"])["x"].sum().unstack()
Frequency table pd.crosstab(df["wicket_kind"], df["phase"], margins=True)
Share within rows pd.crosstab(a, b, normalize="index")
Wide back to long wide.reset_index().melt(id_vars="batter")

Dividing one grid by another works cell by cell, because pandas aligns row and column labels:

top = list(tbl.index[:6])
sub = faced[faced["batter"].isin(top)]
runs_g = sub.pivot_table(index="batter", columns="phase", values="runs_batter", aggfunc="sum")
balls_g = sub.pivot_table(index="batter", columns="phase", values="runs_batter", aggfunc="size")
sr_g = (100 * runs_g / balls_g).round(1)[["powerplay", "middle", "death"]].loc[top]
ct = pd.crosstab(b26["wicket_kind"], b26["phase"], margins=True)
phase            powerplay  middle  death
batter                                   
V Suryavanshi        233.6   240.4  290.0
Shubman Gill         157.9   169.8  148.0
B Sai Sudharsan      142.8   167.0  217.1
V Kohli              174.8   143.1  244.4
H Klaasen            100.0   157.7  177.9
Ishan Kishan         179.8   182.0  193.8
phase            powerplay  middle  death
batter                                   
V Suryavanshi          223      94     10
Shubman Gill           209     215     25
B Sai Sudharsan        243     179     35
V Kohli                206     174     27
H Klaasen               21     265    104
Ishan Kishan           104     194     32
phase                  death  middle  powerplay  All
wicket_kind                                         
bowled                    30      45         39  114
caught                   210     270        175  655
caught and bowled          7       7          8   22
hit wicket                 0       1          1    2
lbw                        8      17          5   30
obstructing the field      0       0          1    1
retired hurt               1       0          1    2
retired out                1       0          0    1
run out                   25      11          5   41
stumped                    1      10          1   12
All                      283     361        236  880

Always print the count grid beside the rate grid: Suryavanshi's 290.0 death strike rate is 10 balls; Klaasen's 177.9 is 104. Note that crosstab sorts columns alphabetically (death, middle, powerplay) — reorder with [["powerplay", "middle", "death"]] or an ordered category (A.10).

Cumulative sums and counters

Worms, fall-of-wicket tables and "balls so far" counters are all cumulative sums within a group. Sort first, then groupby(...).cumsum():

fin = b[b["match_id"] == "1535465"].sort_values("delivery_seq").copy()
fin["cum_runs"] = fin.groupby("innings")["runs_total"].cumsum()
fin["cum_wkts"] = fin.groupby("innings")["is_wicket"].cumsum()
fin["legal_n"] = fin.groupby("innings")["is_legal"].cumsum()       # legal balls so far
fin["ball_no"] = fin.groupby("innings").cumcount() + 1               # deliveries so far
overs = fin.groupby(["innings", "over"]).agg(runs=("runs_total", "sum"), wkts=("is_wicket", "sum"))
overs["cum"] = overs.groupby(level="innings")["runs"].cumsum()
2026 final, end of each innings:
         cum_runs  cum_wkts  legal_n  ball_no
innings                                      
1             155         8      120      124
2             161         5      108      109
over-by-over (first 6 overs of innings 2):
      runs  wkts  cum
over                 
1        5     0    5
2       18     0   23
3       13     0   36
4       19     0   55
5        8     1   63
6        7     1   70

Gujarat Titans 155/8 from 124 deliveries (120 legal balls plus four wides or no-balls); Royal Challengers Bengaluru 161/5 in 108 legal balls — the 18 overs in which they won the 2026 final. The over table shows Rabada's second and fourth overs (overs 2 and 4 of the chase) going for 18 and 19.

Counter Code
running total groupby(key)["x"].cumsum()
row number within group (0-based) groupby(key).cumcount()
running maximum groupby(key)["x"].cummax()
previous ball's value groupby(key)["x"].shift(1)
change since previous ball groupby(key)["x"].diff()

⚠️ Common pitfall: count legal balls; don't infer them from over numbers. "Balls remaining = 120 − 6 × overs" breaks on the eight IPL overs that had five or seven legal balls (Chapter 2, §2.8). Use cumsum() of is_legal, or the toolkit's legal_ball_index.


A.8 Rolling windows

A rolling window computes a statistic over the last n rows — the analyst's "form line". Sort by date first, and roll sums, not ratios: the strike rate over the last ten innings is (sum of runs) ÷ (sum of balls), not the average of ten strike rates.

kb = b[(b["batter"] == "V Kohli") & (b["wides"] == 0)]
k_inns = (kb.groupby(["start_date", "match_id"], as_index=False)
          .agg(runs=("runs_batter", "sum"), balls=("runs_batter", "size"))
          .sort_values(["start_date", "match_id"]).reset_index(drop=True))
r = k_inns[["runs", "balls"]].rolling(window=10, min_periods=10).sum()
k_inns["sr_last10"] = (100 * r["runs"] / r["balls"]).round(1)
k_inns["runs_last10_mean"] = k_inns["runs"].rolling(10).mean().round(1)
k_inns["career_runs"] = k_inns["runs"].cumsum()
Kohli IPL innings with balls faced: 275
start_date match_id  runs  balls  sr_last10  runs_last10_mean  career_runs
2026-05-13  1529300   105     60      164.0              38.7         9145
2026-05-17  1529304    58     37      160.7              41.3         9203
2026-05-22  1529310    15     11      164.3              37.8         9218
2026-05-26  1535462    43     25      168.3              37.2         9261
2026-05-31  1535465    75     42      171.2              42.8         9336
final, chase, 3-over rolling runs per over: [12.0, 16.67, 13.33, 11.33, 8.67, 8.33, 7.0, 6.33, 7.0, 8.33, 8.67, 7.67, 7.67, 6.33, 5.33, 7.33]

The running total ends at 9,336 — Kohli's IPL career runs in the data through the 2026 final — and his strike rate over his last ten IPL innings was 171.2. (This counts innings in which he faced at least one ball; batting_summary also counts innings in which he was at the non-striker's end only.)

Option Effect
rolling(10) NaN until 10 rows exist
rolling(10, min_periods=5) start once 5 rows exist
rolling("365D", on="start_date") a time window instead of a row count (needs sorted dates)
ewm(halflife=10).mean() exponentially weighted — recent innings count more
groupby("batter")["runs"].rolling(10).sum() a separate window per player (returns a MultiIndex; .reset_index(level=0, drop=True) to align)
.shift(1) before rolling use only previous innings — essential when the rolling value is a model feature

⚠️ Common pitfall: rolling windows leak the future into features. A "form" feature for predicting tonight's innings must be built from innings before tonight: rolling(...).sum().shift(1). Chapter 25 builds projections on that rule.


A.9 Dates and season labels

Taught in Chapter 3, §3.8.

season is text, and Cricsheet labels some seasons with two years. start_date is a real datetime64 column — build numeric years from it.

print(len(games[games["season"] == 2026]), len(games[games["season"] == "2026"]),
      len(games[games["season"] == "2020"]))
games["year"] = games["start_date"].dt.year
games["month"] = games["start_date"].dt.month
span = games.groupby("year")["start_date"].agg(["min", "max"]).tail(3)
span["days"] = (span["max"] - span["min"]).dt.days
window = games[games["start_date"].between("2026-05-01", "2026-05-31")]
games[games.season == 2026]: 0 | == '2026': 74 | == '2020': 0
          min   max  size
season                   
2007/08  2008  2008    58
2009/10  2010  2010    60
2020/21  2020  2020    60
IPL matches by month: {3: 78, 4: 578, 5: 492, 6: 4, 9: 27, 10: 56, 11: 8}
             min         max  days
year                              
2024  2024-03-22  2024-05-26    65
2025  2025-03-22  2025-06-03    73
2026  2026-03-28  2026-05-31    64
IPL matches in May 2026: 32 | day names of the last three: ['Wednesday', 'Friday', 'Sunday']
Need Code
calendar year df["start_date"].dt.year
month, weekday .dt.month, .dt.day_name()
date range df["start_date"].between("2026-05-01", "2026-05-31")
days between (d2 - d1).dt.days
parse text to dates pd.to_datetime(s)
a season label → year of its first match Crease: crease.data.season_years(games) (Chapter 2) or crease.explore.season_year(matches) (Chapter 3)

The IPL labels to remember: "2007/08" = 2008, "2009/10" = 2010, "2020/21" = 2020 (played September–November in the UAE). The WPL's 2026 season is "2025/26"; the 2025 Women's ODI World Cup is "2025/26". Appendix B (§B.3) lists the labels for each archive.

⚠️ Common pitfall: "the 2020 IPL has no matches". season == "2020" returns zero rows because the season is stored as "2020/21". Filter on start_date.dt.year == 2020 instead.


A.10 Categories, bins, np.where and np.select

Ordered categories — sort phases in cricket order

order = pd.CategoricalDtype(["powerplay", "middle", "death"], ordered=True)
rr = (b26.assign(phase=b26["phase"].astype(order))
      .groupby("phase", observed=True).agg(runs=("runs_total", "sum"), legal=("is_legal", "sum")))
rr["run_rate"] = (6 * rr["runs"] / rr["legal"]).round(2)
            runs  legal  run_rate
phase                            
powerplay   8887   5278     10.10
middle     12034   7755      9.31
death       6529   3631     10.79

This is the scoreboard run rate — all runs including extras, divided by legal balls — for IPL 2026, matching Chapter 3's 10.10 / 9.31 / 10.79. (Restrict the numerator to legal balls and you get Chapter 3's other table, 9.69 / 8.99 / 10.32; both are correct answers to different questions.)

Categories also save memory

names = ["batter", "bowler", "non_striker", "batting_team", "bowling_team", "venue", "season", "phase"]
cat[names] = cat[names].astype("category")
8 text columns as object: 148.2 MB -> as category: 3.4 MB (whole table 333.9 -> 189.2 MB)

A category column stores each distinct name once and a small integer per row. Use it for repeated text you group by; keep plain text for columns you edit with string methods. When grouping on a category, pass observed=True so empty categories do not appear as rows.

Bins: numbers into bands

first["band"] = pd.cut(first["runs"], bins=[0, 159, 179, 199, 219, 400],
                       labels=["<160", "160-179", "180-199", "200-219", "220+"])
first-innings totals by band, 2024-26: {'<160': 40, '160-179': 37, '180-199': 39, '200-219': 47, '220+': 48}

pd.cut uses edges you choose (right edge included by default); pd.qcut(x, 4) cuts into equal-count quartiles.

Vectorised if/else

x = b26[b26["wides"] == 0]
outcome = np.select([x["is_wicket"], x["runs_batter"] == 0, x["runs_batter"] >= 4],
                    ["wicket", "dot", "boundary"], default="other")
np.where(x["runs_batter"] == 0, 1, 0).mean()
np.select outcome counts, IPL 2026 balls faced: {'other': 7235, 'dot': 4851, 'boundary': 3766, 'wicket': 875}
np.where dot share: 0.3414

np.select takes conditions in priority order: a wicket ball is "wicket" even if no run was scored. That is why the dot share here (wicket balls counted as dots) and the dot count in the np.select line (wicket balls counted separately) differ — say which definition you used. (runs_batter >= 4 also catches the rare all-run four and five; use is_four | is_six for boundaries strictly.)


A.11 Charts: matplotlib, seaborn, plotly

The book's figure conventions (Chapter 7): save with dpi=110, width at most 10 inches, colour-blind-safe palettes (tab10, viridis, the Okabe–Ito colours in crease.charts.COMPARE), never red-versus-green alone; the side batting first in blue, the side batting second in orange, wickets as a red "X". Every figure in a chapter has a written description for readers who cannot see it.

matplotlib — the base layer

import matplotlib.pyplot as plt
BLUE, ORANGE = "#0072B2", "#E69F00"
fig, ax = plt.subplots(figsize=(8, 4.5))
for inn, colour in ((1, BLUE), (2, ORANGE)):
    d = fin[fin["innings"] == inn]
    ax.plot(d["legal_n"], d["cum_runs"], color=colour, lw=2, label=d["batting_team"].iloc[0])
    w = d[d["is_wicket"]]
    ax.scatter(w["legal_n"], w["cum_runs"], marker="X", color="#D55E00", s=60, zorder=3)
ax.set(xlabel="legal balls", ylabel="runs", title="IPL 2026 final — worm built with groupby().cumsum()")
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig(IMAGES / "appa-fig-01-final-worm.png", dpi=110)
plt.close(fig)                                         # free the memory in loops

Worm chart of the IPL 2026 final: cumulative runs against legal balls for both innings, with wickets marked

📊 Figure (described): Cumulative runs (vertical axis) against legal balls (horizontal) for both innings of the IPL 2026 final. Gujarat Titans (blue) finish their 120 legal balls on 155/8; Royal Challengers Bengaluru (orange) are ahead almost from the start, reach 70 by the end of the powerplay and finish on 161/5 after 108 legal balls. Red crosses mark the wickets. The whole chart is three groupby(...).cumsum() columns and two plot calls.

seaborn — statistical charts in one call

import seaborn as sns
fig, ax = plt.subplots(figsize=(7, 4.5))
sns.heatmap(sr_g, annot=balls_g[["powerplay", "middle", "death"]].loc[top], fmt="d", cmap="viridis",
            cbar_kws={"label": "strike rate"}, ax=ax)

Heat map of strike rate by phase for the six leading IPL 2026 run-scorers, each cell labelled with balls faced

📊 Figure (described): A six-by-three grid — batters down the side, powerplay / middle / death across — coloured by strike rate from dark purple (about 100) to yellow (about 290). Each cell is labelled with the balls faced behind it rather than the rate, so the brightest cell (Suryavanshi at the death) is visibly built on just 10 balls and Klaasen's dark powerplay cell on 21, while his 265 middle-overs balls are the season's real sample. Colour shows the rate; the number shows how much to trust it.

Other seaborn calls used in the book: sns.barplot, sns.boxplot, sns.violinplot, sns.scatterplot(..., hue=...), sns.lineplot, sns.histplot, sns.kdeplot. All take data=df, x="col", y="col" and an ax=.

plotly — interactive charts for the browser

import plotly.express as px
pfig = px.line(fin, x="legal_n", y="cum_runs", color="batting_team",
               hover_data=["batter", "bowler", "over"], title="IPL 2026 final (interactive)")
pfig.write_html("worm.html", include_plotlyjs="cdn")    # a small file that loads plotly from the web
plotly traces: ['Gujarat Titans', 'Royal Challengers Bengaluru'] | html bytes: 17162

include_plotlyjs="cdn" keeps the file small (here about 17 KB) but needs an internet connection to view; the default embeds the whole library (several megabytes) and works offline. Chapter 7's crease.charts.interactive_worm and the Chapter 39 dashboard use plotly.

Chart cheat sheet

Chart Call
line / worm ax.plot(x, y)
bar (Manhattan) ax.bar(x, height); horizontal: ax.barh
scatter ax.scatter(x, y, s=size, c=colour)
histogram ax.hist(x, bins=30) or sns.histplot
grid of panels fig, axes = plt.subplots(2, 3, sharey=True)
reference line ax.axhline(y, ls="--"), ax.axvline(x)
text label ax.annotate("text", xy=(x, y))
log scale ax.set_yscale("log")
save fig.savefig(path, dpi=110, bbox_inches="tight") then plt.close(fig)

Appendix K collects every chart type in the book with its code: Appendix K.


A.12 scikit-learn: fit, predict, cross-validate

Every model in the book follows one pattern: build a feature table X (one row per example) and a target y; wrap preprocessing and the model in a pipeline; estimate out-of-sample performance with cross-validation; fit on the past and test on the future before you believe anything.

The worked example: from the state of an IPL chase at the end of an over — runs needed, balls left, wickets in hand — did the chasing side win? (This is a toy version of the win-probability model of Chapter 20; Chapter 9 builds the table-based version.)

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.model_selection import GroupKFold, StratifiedKFold, cross_val_score, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

ok = games[games["method"].isna() & games["winner"].notna() & (games["overs_per_side"] == 20)]
ch = b[(b["innings"] == 2) & b["match_id"].isin(ok["match_id"])].sort_values(["match_id", "delivery_seq"]).copy()
ch["cum_runs"] = ch.groupby("match_id")["runs_total"].cumsum()
ch["cum_wkts"] = ch.groupby("match_id")["is_wicket"].cumsum()
ch["legal_n"] = ch.groupby("match_id")["is_legal"].cumsum()
ends = ch[ch["legal_n"].isin(range(30, 109, 6))]                     # end of overs 5, 6, ..., 18
state = ends.groupby(["match_id", "legal_n"], as_index=False).last()
state = state[(state["target_overs"] == 20) & (state["cum_runs"] < state["target_runs"])]
X = pd.DataFrame({"runs_needed": state["target_runs"] - state["cum_runs"],
                  "balls_left": 120 - state["legal_n"],
                  "wkts_in_hand": 10 - state["cum_wkts"]})
y = (state["batting_team"] == state["match_id"].map(ok.set_index("match_id")["winner"])).astype(int)
groups = state["match_id"]

model = make_pipeline(StandardScaler(), LogisticRegression())
naive = cross_val_score(model, X, y, cv=StratifiedKFold(5, shuffle=True, random_state=2026), scoring="roc_auc")
res = cross_validate(model, X, y, cv=GroupKFold(n_splits=5), groups=groups,
                     scoring=["roc_auc", "neg_brier_score"])

train, test = yr < 2023, yr >= 2023                     # yr = year of each state's match
model.fit(X[train], y[train])
p = model.predict_proba(X[test])[:, 1]                  # probability of class 1 (chasing side wins)
states (end of overs 5-18 of 1185 chases; no D/L, with a winner): 15,803; chasing side won 0.531 of states
StratifiedKFold AUC (rows of one match leak across folds): [0.894, 0.883, 0.879, 0.885, 0.892] mean 0.887
GroupKFold by match AUC: [0.905, 0.868, 0.893, 0.869, 0.895] mean 0.886 | Brier 0.1369
time split: train 2008-2022 n=12,106, test 2023-2026 n=3,697; test AUC 0.902, Brier 0.1364, mean predicted 0.426 vs actual 0.514
standardised coefficients: {'runs_needed': -2.761, 'balls_left': 1.565, 'wkts_in_hand': 1.097}
P(chasing side wins), trained on 2008-2022: {'100 off 60, 8 in hand': 0.434, '54 off 30, 8 in hand': 0.726}

How to read it:

  • Groups. Each chase contributes up to 14 rows (one per over), and rows from the same match are not independent. GroupKFold keeps all of a match's rows in the same fold. Here the leak barely mattered (0.887 against 0.886), but on player-level or season-level data it routinely inflates scores — use groups whenever rows share a match, a player or a season.
  • Time split. Trained on 2008–2022 and tested on 2023–2026, the model ranks chases well (AUC 0.902) but its average forecast is 0.426 against an actual 0.514: it underrates modern chasers by about nine points. The game changed under the model — the same lesson Chapter 9 draws for its win-probability table. Cross-validation that shuffles across years would never have shown this.
  • Coefficients are on the standardised scale (after StandardScaler), so their sizes are comparable: runs needed matters most, then balls left, then wickets in hand.
  • predict_proba(X)[:, 1] gives probabilities; predict(X) gives hard 0/1 labels, which you almost never want for cricket forecasting. Score probabilities with the Brier score and log loss, check calibration (Chapter 20), and report AUC only as a ranking measure.

The pattern, in one table:

Step Code
features and target X = df[feature_cols], y = df["won"]
pipeline make_pipeline(StandardScaler(), LogisticRegression()) (swap in RandomForestClassifier(random_state=…), GradientBoostingClassifier, xgboost.XGBClassifier)
cross-validate cross_val_score(model, X, y, cv=GroupKFold(5), groups=match_ids, scoring="neg_brier_score")
time-aware CV TimeSeriesSplit(n_splits=5) on rows sorted by date, or a manual "fit before year Y, test after"
fit model.fit(X_train, y_train)
predict model.predict_proba(X_new)[:, 1]
inspect model.named_steps["logisticregression"].coef_
reproducibility random_state= on every splitter and model that takes one
regression instead LinearRegression, Ridge, GradientBoostingRegressor; score with neg_mean_absolute_error

⚠️ Common pitfall: fitting the scaler (or anything) on all the data before splitting. Put every preprocessing step inside the pipeline so cross-validation refits it on each training fold. A scaler, an imputer or a target encoding fitted on the whole table quietly leaks the test set into training.


A.13 Common errors and their fixes

Read a traceback from the bottom up: the last line says what went wrong, the lines above say where (Chapter 3, §3.9). The script reproduces the most common ones and catches them:

column name case: KeyError: 'Runs_batter'
`and` between Series: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
missing brackets: TypeError: Cannot perform 'rand_' with a dtyped [bool] array and scalar of type [bool]
wrong file name: FileNotFoundError: [Errno 2] No such file or directory: 'data/processed/ipl_delivery.parquet'
emoji to a cp1252 console: UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f9ea' in position 0: character maps to <undefined>
assign to a filtered slice -> ['SettingWithCopyWarning']
Kohli SR with wides counted as balls: 131.07 | correct: 134.8

Errors that stop the program

Last line of the traceback What you did Fix
ModuleNotFoundError: No module named 'cricdata' ran a script without the header, or from a copied file whose parents[n] no longer reaches the book folder use the A.1 header; check BOOK points at the book root
ModuleNotFoundError: No module named 'pandas' (or any library) the virtual environment is not active, or the library isn't installed in it activate .venv; pip install -r requirements.txt
an import error mentioning a Parquet engine pyarrow missing pip install pyarrow
KeyError: 'Runs_batter' a column name that doesn't exist (names are case-sensitive) print(balls.columns.tolist()) and copy the name
AttributeError: 'DataFrame' object has no attribute 'Phase' the same, with dot access use balls["phase"]
ValueError: The truth value of a Series is ambiguous… and / or between two Series & / \| with brackets round each condition
TypeError: Cannot perform 'rand_' with a dtyped […] array… missing brackets: balls["phase"] == "death" & … — & binds tighter than == (balls["phase"] == "death") & (…)
FileNotFoundError: … No such file or directory a typed path is wrong use the toolkit loaders, or build paths from BOOK
UnicodeEncodeError: 'charmap' codec can't encode character… printing Unicode (🧪, dashes, accented names) to a cp1252 Windows stream PYTHONIOENCODING=utf-8 (A.1) or python -X utf8
UnicodeDecodeError reading a file opened a UTF-8 file with the system default encoding open(path, encoding="utf-8")
ZeroDivisionError: division by zero a rate with a zero denominator in plain Python guard: None if balls == 0 else …; pandas gives inf/NaN instead — use .where(den > 0) as the toolkit does
IndexError: list index out of range last_over[6] — positions run 0–5 count from zero
MemoryError, or the laptop freezes loaded the full Tests table (≈2 GB) columns= (A.3, A.14)
ValueError: Grouper for 'innings' not 1-dimensional an older toolkit version with batting_summary(by=[…, "innings"]) update the toolkit; the current one handles it (rename the innings index level before reset_index())
MergeError: Merge keys are not unique in right dataset… validate="many_to_one" caught a duplicated key deduplicate the right table, or merge on more columns

Warnings worth reading

Warning Meaning Fix
SettingWithCopyWarning you added a column to a filtered slice; pandas can't tell whether you meant to change the original filter with .copy(); in pandas 3 (copy-on-write) the warning disappears and the slice behaves as a copy
FutureWarning: … concatenation with empty or all-NA entries… pd.concat of tables where some columns are entirely missing (e.g. Tests have no target_runs) concatenate only the columns you need, or drop all-NA columns first
FutureWarning about observed=False grouping by a category column pass observed=True

Bugs that don't crash — the dangerous ones

Symptom Cause Fix
a filter returns 0 rows season == 2026 (number) or season == "2020" (label is "2020/21") filter on text, or on start_date.dt.year
Kohli's IPL strike rate 131.07 instead of 134.80 counted wides as balls faced balls faced = wides == 0
numbers differ slightly from the book super-over balls included ~balls["super_over"]
a "player" with an impossible record two people share a display name (IPL: "Harmeet Singh"; men's T20Is: three "Rashid Khan"s) group by batter_id / bowler_id, or only_player(balls, name) — Appendix B, §B.4
run rates a few percent low filtered to legal balls, so wides and no-ball runs vanished from the numerator sum runs_total over all deliveries, divide by legal balls
& used where \| was meant is_four & is_six is never true read the condition aloud
a merge adds rows non-unique key on the right validate=, compare row counts
a team's history looks short franchise renamed ("Delhi Daredevils" → "Delhi Capitals") map old names to new before grouping
strike-rate leaderboard full of cameos no minimum sample minimum balls, or shrinkage
percentages that don't match a published figure different definition (dot ball with or without wicket balls; legal or all deliveries) write the definition next to the number

A.14 Performance

The whole book runs on an old laptop if you follow five rules.

1. Read only the columns you need. The single largest saving. Men's Test deliveries: 1,970 MB with all 42 columns, 239.8 MB with five (A.3). IPL: 333.9 MB → 75.8 MB with nine.

2. Push row filters into the read. pd.read_parquet(path, columns=cols, filters=[("season", "==", "2026")]) loaded one IPL season — 17,527 rows, 4.5 MB — without ever building the other 278,000 rows. filters= accepts ==, !=, <, >, <=, >=, in and not in; a list of tuples means "and".

3. Store repeated text as categories. Eight name and label columns of the IPL table shrank from 148.2 MB to 3.4 MB as categories; the whole table from 333.9 MB to 189.2 MB (A.10).

4. Vectorise; never loop over rows.

IPL 2026 runs/balls by batter: itertuples loop 0.040 s, groupby 0.004 s; same answer: True

Even the fastest Python loop (itertuples) was about ten times slower than groupby on one season; Chapter 3 timed iterrows over the whole IPL at 5.381 s against 0.050 s for groupby — about 107 times faster on that run. If you are writing for row in over a DataFrame, look for the column-wise version: boolean masks, groupby, np.where, np.select, cumsum, shift.

5. Parse once, cache forever. The toolkit parses each Cricsheet zip once into Parquet; reading the IPL cache took 0.16 s above, against seconds to minutes for the JSON parse (Chapter 2, §2.6: Tests 15.8 s to parse, 0.66 s to read). Crease's data.load() adds an in-memory cache so a session reads each file once. The cache never refreshes itself — see Appendix B, §B.6 for build(code, force=True).

Smaller habits:

Habit Why
filter rows before groupby and merge less data through every later step
del big_df when done with it frees memory in long scripts
plt.close(fig) after savefig figures in a loop otherwise accumulate
observed=True on category groupbys no empty-category rows
value_counts() before unique() on big columns you usually want the counts anyway
tracking simulation on a whole competition, then filter the simulated values depend on the rows passed in; this keeps every chapter's numbers identical (Appendix B, §B.6)
time a step with time.perf_counter() find the slow line before optimising

A.15 "I want to…" index

I want to… Use See
load a competition load_deliveries("ipl"), load_matches("ipl") A.3, B.6
load several competitions load_many([...]) or pd.concat of read_parquet(columns=…) A.3
see what columns exist balls.columns; Appendix B §B.1 B.1
keep only one phase / season / player boolean mask, isin, between A.4
drop super overs balls[~balls["super_over"]] A.4
count balls faced wides == 0, then size A.5
get batting / bowling tables batting_summary(balls, by=[...]), bowling_summary(...) A.5, B.6
add a group total to every row groupby(...).transform("sum") A.5
attach match results merge(games[[...]], on="match_id", how="left", validate="many_to_one") A.6
make a batter × phase grid pivot_table (rates and counts) A.7
build a worm / fall of wickets sort, groupby("innings").cumsum() A.7
compute form over the last n innings rolling sums, then divide; shift(1) for features A.8
turn season labels into years start_date.dt.year A.9
sort phases in cricket order ordered CategoricalDtype A.10
band totals pd.cut A.10
label each ball's outcome np.select A.10
draw a chart matplotlib / seaborn / plotly A.11
fit and validate a model pipeline + GroupKFold + time split A.12
fix a UnicodeEncodeError PYTHONIOENCODING=utf-8 A.1, A.13
pin one player across leagues only_player(balls, name) or group by id B.4, B.6
look up a player's bowling style data/reference/player_styles.csv B.5
get pace/spin onto deliveries crease.bowling_types.add_styles (Chapter 18) B.7
run R instead Appendix J

Further reading: Wes McKinney, Python for Data Analysis (the pandas reference, by its creator), and the official pandas, matplotlib, seaborn, plotly and scikit-learn user guides. Hadley Wickham's R for Data Science teaches the same split–apply–combine thinking in R.