55 min read

Ahmedabad, 3 June 2025. The IPL final. Royal Challengers Bengaluru have made 190 for 9, and Punjab Kings, chasing 191, reach the start of the last over on 162 for 7. They need 29 off six balls. Josh Hazlewood bowls to Shashank Singh.

Chapter 3 — Python and pandas for Cricket: Wrangling Ball-by-Ball Data from Your First Line of Code

Ahmedabad, 3 June 2025. The IPL final. Royal Challengers Bengaluru have made 190 for 9, and Punjab Kings, chasing 191, reach the start of the last over on 162 for 7. They need 29 off six balls. Josh Hazlewood bowls to Shashank Singh.

The first ball is a dot. So is the second. The match is gone, and everyone in the stadium knows it. Then Shashank hits the third ball for six, the fourth for four, the fifth for six and the sixth for six. Twenty-two runs off the over. It is not enough. Royal Challengers Bengaluru win by six runs, and lift the trophy for the first time in the competition's history.

Eleven hundred miles away in Dhaka, Nusrat Jahan watched that over on a phone stream that kept buffering. Afterwards she opened a laptop she had never written a line of code on, opened a Python window, and typed this:

last_over = [0, 0, 6, 4, 6, 6]
sum(last_over)

Python answered 22.

That is the whole chapter in miniature. A real over became a list; a question ("how many did he get?") became a function (sum); and the computer answered instantly, correctly and without commentary. By the end of this chapter you will be able to go from that one line to rebuilding the entire scorecard of that final — every batter, every bowler, every extra, the fall of wickets, the run-rate chart — from nothing but the 252 deliveries recorded in the data, and you will have written the code that does the same for any of the 1,243 IPL matches, or any T20I, women's ODI or WPL game, in the book's data snapshot.

Here is the bit most programming books get wrong for people like Nusrat. They teach you Python with shopping lists and temperatures, and only at the end do you get to the thing you care about. We will do it the other way round. Every idea in this chapter — variables, lists, loops, dictionaries, functions, and then pandas DataFrames, filtering, groupby, merge, pivot_table, missing values, dates and charts — arrives attached to a cricket question, and every answer is computed from real ball-by-ball data. When you learn what a loop is, you will use it to count Virat Kohli's singles in that final. When you learn groupby, you will use it to produce the 2026 IPL run-scorers' table. When you learn about missing values, you will discover why the IPL's 2020 season is stored as the text '2020/21', and why that silently breaks the code most beginners write.

You need no programming experience. You need Python installed and the book's data downloaded (both covered in Chapter 2). If you can follow a scorecard, you can follow this chapter.

🏏 Fan Track: Read every section's opening cricket question and the "what it means" paragraphs; run the code in §3.1–3.3 yourself even if you skip the rest. The scorecard rebuild in §3.10 is worth doing line by line — it will change how you read a scorecard.

📊 Analyst Track: If you already write Python, skim §3.1–3.3 and slow down from §3.4. Pay attention to the pitfalls — the season-as-text trap, wides in the balls-faced count, super overs, and no-result innings dragging down averages. Every later chapter assumes the groupby → merge → pivot_table workflow taught here.

🏆 Fantasy Track: §3.6 (leaderboards with minimum-sample filters) and §3.7 (phase strike-rate pivot tables) are the two techniques you will use most when picking a team. The project module explore.py gives you a top-N table for any competition in one line.


3.1 Your First Line of Code: A Batter in Three Variables

The cricket question: Virat Kohli made 43 off 35 balls in that final. What was his strike rate?

You know how to do this on a calculator: 43 divided by 35, times 100. Python is, at first, a very fussy calculator with a memory. The memory is the important part. In Python you give a value a name, and from then on you use the name:

batter = "V Kohli"          # a string (text)
runs = 43                   # an integer (whole number)
balls = 35                  # another integer
strike_rate = 100 * runs / balls
print(batter, "scored", runs, "off", balls, "balls")
print("strike rate:", strike_rate)
print("rounded:", round(strike_rate, 2))

Each line with an = sign creates a variable: a name attached to a value. The = does not mean "equals" in the mathematical sense; read it as "is now". runs = 43 means "the name runs now refers to 43". The text after # is a comment — Python ignores it; it is for you.

Run this (the full script is code/01_python_basics.py; from the chapter directory type python code/01_python_basics.py) and Python prints:

V Kohli scored 43 off 35 balls
strike rate: 122.85714285714286
rounded: 122.86
types: str int float
f-string: V Kohli 43 (35) SR 122.86

Three kinds of value appeared. "V Kohli" is a string (str) — text, always in quotes. 43 is an integer (int). And strike_rate is a float — a number with a decimal point, which Python produces whenever you divide. You will meet these three types in every cricket dataset: names are strings, counts are integers, rates are floats.

The last line used an f-string, Python's tidiest way to build text from values:

print(f"{batter} {runs} ({balls}) SR {strike_rate:.2f}")

The f before the quote mark says "fill in the curly brackets", and :.2f inside a bracket says "as a float with two decimal places". That one line is how every scorecard in this book gets printed.

📐 Definition: Strike rate (SR) for a batter = 100 × runs off the bat ÷ balls faced, where balls faced excludes wides (a wide is not a ball the batter could score off) but includes no-balls. It is "runs per 100 balls". This is the book's standard definition, identical in every chapter.

So Kohli's 43 off 35 was a strike rate of 122.86 in a final where, as we will see, his team made 190. Was that good? You cannot tell from one number — which is exactly why we need the rest of this chapter. A strike rate means something only next to other strike rates: the same batter in other matches, other batters in the same match, the same phase of other innings. Python's job is to make producing those comparisons effortless.


3.2 Lists and Loops: An Over Is a List

The cricket question: In that last over, how many sixes did Shashank hit, and how short of the target did Punjab finish?

An over is a sequence of balls in order. Python's word for an ordered sequence is a list, written in square brackets with commas between the items:

last_over = [0, 0, 6, 4, 6, 6]
needed = 29
print("len(last_over)  =", len(last_over))
print("sum(last_over)  =", sum(last_over))
print("first ball      =", last_over[0])
print("last ball       =", last_over[-1])
print("balls 3 to 6    =", last_over[2:])
print("sixes in over   =", last_over.count(6))
print("biggest hit     =", max(last_over))
print("short by        =", needed - sum(last_over))
last_over       = [0, 0, 6, 4, 6, 6]
len(last_over)  = 6
sum(last_over)  = 22
first ball      = 0
last ball       = 6
balls 3 to 6    = [6, 4, 6, 6]
sixes in over   = 3
biggest hit     = 6
short by        = 7

Several things to notice, because they trip up every beginner.

Counting starts at zero. last_over[0] is the first ball. last_over[5] is the sixth. Cricket counts balls 1 to 6; Python counts positions 0 to 5. It feels wrong for about a week and then it doesn't.

Negative positions count from the end. last_over[-1] is the last ball, last_over[-2] the second-last. Handy when you want "the final over of an innings" without knowing how many overs there were.

Slicing. last_over[2:] means "from position 2 to the end" — balls three to six. The general form my_list[start:stop] includes start and stops before stop, so last_over[0:2] is the first two balls, [0, 0].

Built-in functions. len, sum, max and min work on any list of numbers. .count(6) is a method — a function that belongs to the list and is called with a dot.

Twenty-two off the over, seven short of the 29 needed. Punjab finished 184 for 7 chasing 191 — beaten by six runs, because 190 would have tied.

Loops: going through an innings ball by ball

Now a longer list: every ball Kohli faced in that final, in order, with the runs he scored off each (wides removed — more on that in a moment).

kohli = [1, 1, 4, 1, 1, 1, 2, 1, 0, 1, 1, 2, 1, 1, 1, 0, 1, 1,
         1, 4, 1, 1, 1, 0, 2, 1, 1, 1, 1, 4, 1, 1, 1, 1, 0]

How many dot balls? How many singles? You could count by eye. A loop counts for you:

dots = 0
fours = 0
singles = 0
for r in kohli:
    if r == 0:
        dots = dots + 1
    elif r == 4:
        fours += 1
    elif r == 1:
        singles += 1
print("dots:", dots, " singles:", singles, " fours:", fours)

Read for r in kohli: as "for each ball in Kohli's innings, call its runs r, and do the indented lines". The indentation (four spaces) is not decoration: it is how Python knows which lines belong inside the loop. if, elif ("else if") and else choose what to do; == tests for equality (one = assigns, two compare). dots += 1 is shorthand for dots = dots + 1.

balls faced: 35  runs: 43
dots: 4  singles: 25  fours: 3
comprehension dots: 4
list.count singles: 25
runs from singles: 25 of 43 = 58.1%
running total after balls 1-10: [1, 2, 6, 7, 8, 9, 11, 12, 12, 13]
first ball on which he passed 20: 18

Twenty-five singles out of 35 balls; only four dots and three fours. More than half his runs — 58.1% — came in ones. Whatever you think of that innings, it was not a slog: it was a batter rotating strike on a big occasion, and it ended in the 15th over with RCB on 131. The script also builds a running total — appending each new cumulative score to a list — which is exactly the data behind a "worm" chart:

running, total = [], 0
for r in kohli:
    total += r
    running.append(total)

[] is an empty list; .append(x) adds x to the end. Two lines like this, applied to a whole innings, give you the line in Figure 3.1.

Cumulative runs ball by ball for Kohli (43 off 35) and Shashank Singh (61 not out off 30) in the IPL 2025 final

📊 Figure (described): Two lines of cumulative runs against balls faced in the IPL 2025 final. Kohli's red line climbs steadily and almost straight — a run a ball for most of his 35 balls — to 43. Shashank Singh's blue line is flat-ish early and then jumps in steps of four and six at the end, reaching 61 not out off 30. Same match, two completely different shapes of innings.

There is also a compact one-line form of a loop called a list comprehension, which builds a new list by filtering an old one:

len([r for r in kohli if r == 0])     # 4 dot balls
sum(r for r in kohli if r == 1)       # 25 runs from singles

Read it as English: "r, for each r in kohli, if r equals 0". You will see comprehensions all over Python code; we will use them sparingly.

🔄 Check your understanding 1. last_over = [0, 0, 6, 4, 6, 6]. What does last_over[1:4] return? 2. Write one line that gives the number of boundaries (fours or sixes) in kohli. 3. Why does Python say Kohli faced 35 balls when the data has 36 rows with him on strike?

Answer

  1. [0, 6, 4] — positions 1, 2 and 3 (the second, third and fourth balls); the slice stops before position 4.
  2. len([r for r in kohli if r in (4, 6)]) → 3 (or kohli.count(4) + kohli.count(6)).
  3. One of the 36 deliveries was a wide (over 13, ball 5). A wide is not a ball faced — the batter could not hit it — so the standard "balls faced" count excludes it. The script confirms: rows where Kohli was on strike (incl. wides): 36, Kohli balls faced (no wides): 35.

Checking your typing against the data

I typed Kohli's list by hand from the ball-by-ball file. Hand-typing is how errors creep into cricket statistics — a misread scorecard, a transposed digit — so the script ends by loading the real data and checking:

balls_df = load_deliveries("ipl")
final = balls_df[balls_df["match_id"] == "1473511"]
k = final[(final["batter"] == "V Kohli") & (final["wides"] == 0)]
print("hand-typed list matches data:", k["runs_batter"].tolist() == kohli)
rows where Kohli was on strike (incl. wides): 36
Kohli balls faced (no wides): 35  runs: 43
hand-typed list matches data: True
last over from data: [0, 0, 6, 4, 6, 6]  matches: True
RCB total: 190  PBKS after 19 overs: 162  needed off 20th: 29

Those lines use pandas, which we have not met yet. Don't worry about the details; notice the habit. Every number you type by hand should be checked against the data at least once. That habit is the difference between this book and the numbers people quote from memory.


3.3 Dictionaries and Functions: A Scorecard Line and a Strike-Rate Machine

The cricket question: How do we store one line of a scorecard — name, runs, balls, fours, sixes, how out — and how do we stop rewriting the strike-rate formula every time?

A list is ordered by position. A scorecard line is better described by labels: the runs, the balls, the dismissal. Python's labelled container is the dictionary (dict), written with curly brackets and key: value pairs:

line = {"batter": "V Kohli", "runs": 43, "balls": 35, "fours": 3, "sixes": 0,
        "how_out": "c & b Azmatullah Omarzai"}
print(line["runs"])                                   # 43
line["strike_rate"] = round(100 * line["runs"] / line["balls"], 2)

You look values up by key — line["runs"] — instead of by position. Assigning to a new key adds it. A whole batting card is then a list of dictionaries, one per batter:

card = [
    {"batter": "PD Salt",    "runs": 16, "balls": 9},
    {"batter": "V Kohli",    "runs": 43, "balls": 35},
    {"batter": "MA Agarwal", "runs": 24, "balls": 18},
    {"batter": "RM Patidar", "runs": 26, "balls": 16},
]
for entry in card:
    print(f"{entry['batter']:<12}{entry['runs']:>4}{entry['balls']:>4}")
PD Salt       16   9
V Kohli       43  35
MA Agarwal    24  18
RM Patidar    26  16

(:<12 means "left-align in 12 characters", :>4 "right-align in 4" — f-strings can lay out columns.) Hold on to this picture — a list of dictionaries, each with the same keys — because it is exactly what a pandas DataFrame is, conceptually: rows of labelled values. When we reach §3.4 you will already understand tables.

Functions: write it once

We have computed 100 * runs / balls three times already. A function packages a calculation under a name so you write it once and use it forever:

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


def economy(runs_conceded, legal_balls):
    """Runs conceded per six legal balls (per over)."""
    if legal_balls == 0:
        return None
    return round(6 * runs_conceded / legal_balls, 2)

def begins a function; runs and balls are its parameters (the inputs); return hands back the answer. The triple-quoted line is a docstring, the function's own documentation. Now:

PD Salt 177.78
V Kohli 122.86
MA Agarwal 133.33
RM Patidar 162.5
Shashank Singh 61 off 30: 203.33
Krunal Pandya 4-0-17-2 economy: 4.25
Kyle Jamieson 4-0-48-3 economy: 12.0
A batter who never faced: None

Look at the two bowling lines. Kyle Jamieson took three wickets for Punjab in that final and conceded 48 off his four overs; Krunal Pandya took two for RCB and conceded 17. Pandya was named player of the match. A wicket column alone would rank Jamieson higher. Economy — another single number — ranks Pandya higher. Neither tells the whole story, which is Theme 1 of this book in one comparison: the traditional single-number summaries mislead unless you look at several together, and in context. Chapter 4 is devoted to exactly this.

📐 Definition: Economy rate = 6 × runs conceded ÷ legal balls bowled — runs per over. Runs conceded includes wides and no-balls (they are charged to the bowler) but excludes byes, leg-byes and penalty runs.

🧩 Productive struggle Before reading on, look at batting_strike_rate and answer: why is the if balls == 0 check there at all? What would happen without it, for a batter who came in at the non-striker's end and was run out without facing? And is returning None better than returning 0?

Answer

Without the check, Python would try 100 * 0 / 0 and stop with a ZeroDivisionError (you will see that exact error in §3.9). It happens in real matches: a batter run out at the non-striker's end without facing has 0 balls. Returning 0 would be wrong — it would claim the batter scored at a strike rate of zero, as if he had faced balls and blocked them all. None (Python's "no value") says honestly "undefined". pandas uses the same idea with NaN, "not a number", and the toolkit's batting_summary reports the average as NaN for a batter who has never been dismissed rather than pretending it is infinite. Choosing what to return for the impossible case is a real analytical decision, not a programming detail.


3.4 From Lists to DataFrames: 295,732 Deliveries in One Object

The cricket question: Lists are fine for one over. What about every ball ever bowled in the IPL?

You will not type those by hand. The toolkit you set up in Chapter 2 has already flattened Cricsheet's ball-by-ball files into tables, and pandas — Python's table library — loads them in one line. Every code file in this book starts with the same short header that tells Python where the toolkit lives:

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

You do not need to understand every line yet. import loads a library; the sys.path lines tell Python to look in the book's toolkit/ and project/ folders; matplotlib.use("Agg") makes charts save to files instead of opening windows. The last line brings in four functions from toolkit/cricdata.py. Then:

import pandas as pd
balls = load_deliveries("ipl")
print("type:", type(balls).__name__)
print("shape (rows, columns):", balls.shape)
print(balls[["season", "batting_team", "over", "ball_in_over", "batter",
             "bowler", "runs_batter", "runs_total"]].head(5).to_string())
type: DataFrame
shape (rows, columns): (295732, 42)
first 12 column names: ['match_id', 'competition', 'match_type', 'innings', 'super_over', 'batting_team', 'bowling_team', 'over', 'ball_in_over', 'legal_ball_index', 'delivery_seq', 'batter']

  season         batting_team  over  ball_in_over     batter    bowler  runs_batter  runs_total
0   2017  Sunrisers Hyderabad     1             1  DA Warner  TS Mills            0           0
1   2017  Sunrisers Hyderabad     1             2  DA Warner  TS Mills            0           0
2   2017  Sunrisers Hyderabad     1             3  DA Warner  TS Mills            4           4
3   2017  Sunrisers Hyderabad     1             4  DA Warner  TS Mills            0           0
4   2017  Sunrisers Hyderabad     1             5  DA Warner  TS Mills            0           2

import pandas as pd is a convention every pandas user follows: the library is called pd from then on. balls is a DataFrame — a table with 295,732 rows (one per delivery, legal or not, across every IPL match in the data) and 42 columns. .shape gives (rows, columns); .head(5) shows the first five rows. The numbers down the left (0, 1, 2…) are the index, pandas' row labels.

Look at the fifth row: runs_batter 0 but runs_total 2. Something other than the bat produced two runs — leg-byes, byes or a wide. That single row is a reminder that a ball-by-ball file records more than a scorecard does, and that "runs" means different things in different columns. The full column list is documented in Appendix B; the ones you will use constantly are match_id, season, innings, over (1-based, so the first over is 1), batter, bowler, non_striker, runs_batter, runs_extras, runs_total, wides, noballs, is_legal, is_four, is_six, is_wicket, wicket_kind, player_out and phase.

A column is a Series

Pick one column with square brackets and you get a Series — a single labelled column, which behaves like a list that knows arithmetic:

rb = balls["runs_batter"]
print("total runs off the bat, every IPL ball:", int(rb.sum()))
print("mean runs off the bat per delivery:", round(rb.mean(), 3))
print(rb.value_counts().sort_index().to_string())
type: Series  length: 295732
total runs off the bat, every IPL ball: 381529
mean runs off the bat per delivery: 1.29
most runs off one delivery: 6

value_counts of runs off the bat:
runs_batter
0    116759
1    109492
2     18338
3       843
4     34447
5        74
6     15779

In one line, .sum() added up 381,529 runs off the bat — every run scored off the bat in the IPL's history to the end of the 2026 season, in the Cricsheet data. .value_counts() counted each distinct value: 116,759 deliveries with nothing off the bat, 109,492 singles, 34,447 fours, 15,779 sixes. Seventy-four fives, which can only come from overthrows or the rare all-run five; the data records the runs, not how they happened.

Notice what we did not write: a loop. We did not say "for each of 295,732 rows, add the runs". We asked the Series for its sum, and pandas did the looping internally, in fast compiled code. This style — operating on whole columns at once — is called vectorisation, and learning to think in it is the main skill of this chapter.

⚠️ Common pitfall: runs_total is not "runs scored by the batter". runs_total includes extras (wides, no-balls, byes, leg-byes, penalties); runs_batter is off the bat only. Team totals and run rates use runs_total. Batting statistics use runs_batter. Bowling figures use a third quantity, runs conceded, which is runs_total minus byes, leg-byes and penalties (the toolkit's runs_conceded() function). Mixing them up produces numbers that look plausible and are wrong by a few percent — the most dangerous kind of wrong.

🔄 Check your understanding 1. What is the difference between a DataFrame and a Series? 2. From the value_counts output, roughly what share of all IPL deliveries produced a boundary off the bat? 3. Which column would you sum to get a team's total, and which to get a batter's runs?

Answer

  1. A DataFrame is a whole table (rows × columns); a Series is one labelled column of it. balls is a DataFrame; balls["runs_batter"] is a Series.
  2. Fours 34,447 plus sixes 15,779 = 50,226 of 295,732 deliveries, about 17%. (That counts every delivery, wides and no-balls included, in the denominator; per legal ball the share is slightly higher. Definitions again.)
  3. runs_total for the team (it includes extras); runs_batter for the batter.

3.5 Filtering: Asking the Data a Question

The cricket question: Is the death really where the runs come? What happens on a typical legal ball in each phase of the 2026 IPL?

Almost every cricket question begins with "only the balls where…": only the death overs, only this season, only this bowler. In pandas you write that condition as a comparison on a column:

is_death = balls["phase"] == "death"
death = balls[is_death]

The first line produces a boolean mask — a Series of True/False, one per delivery, True where the phase is "death" (overs 16–20 in T20 cricket; the toolkit labels every delivery with its phase). The second line uses the mask inside square brackets to keep only the True rows. This is the single most common line of pandas you will ever write.

the mask is a Series of bool - first five: [False, False, False, False, False]
death-over deliveries, all IPL seasons: 67173
IPL 2026 deliveries: 17527  matches: 74
IPL 2026 legal balls (no super overs): 16664

📐 Definition: Phases (T20). Powerplay = overs 1–6, middle = overs 7–15, death = overs 16–20 (1-based). In ODIs: powerplay 1–10, middle 11–40, death 41–50. The toolkit stores this in the phase column, so every chapter uses identical boundaries. Tests have no phases ("none").

To combine conditions, use & ("and"), | ("or") and ~ ("not"), and put each condition in its own brackets:

b26 = balls[balls["season"] == "2026"]
legal26 = b26[b26["is_legal"] & ~b26["super_over"]]

~b26["super_over"] flips the super-over flag: keep the balls that are not in a super over. Then a small loop over the three phases builds a table:

rows = []
for ph in ["powerplay", "middle", "death"]:
    p = legal26[legal26["phase"] == ph]
    rows.append({
        "phase": ph,
        "legal_balls": len(p),
        "runs_per_over": round(6 * p["runs_total"].sum() / len(p), 2),
        "dot_pct": round(100 * (p["runs_total"] == 0).mean(), 1),
        "boundary_pct": round(100 * (p["is_four"] | p["is_six"]).mean(), 1),
        "wicket_pct": round(100 * p["is_wicket"].mean(), 2),
    })
phase_tbl = pd.DataFrame(rows)

Two tricks hide in there. First, (p["runs_total"] == 0).mean(): the mean of a True/False column is the share that are True, because Python treats True as 1 and False as 0. That is how you compute any percentage in pandas. Second, look at the last line — pd.DataFrame(rows) turns a list of dictionaries into a table, exactly the picture from §3.3.

IPL 2026 by phase (legal balls only):
    phase  legal_balls  runs_per_over  dot_pct  boundary_pct  wicket_pct
powerplay         5278           9.69     41.4          26.7        4.45
   middle         7755           8.99     28.4          18.8        4.63
    death         3631          10.32     29.1          24.0        7.74

This little table is worth reading slowly, because it overturns a piece of received wisdom. In the 2026 IPL the powerplay had the most dot balls (41.4% of legal balls) and the highest boundary rate (26.7%) — feast or famine, batters swinging against two fielders out. The death had the highest run rate (10.32 an over, on legal balls only) but a boundary rate below the powerplay's; what makes the death different is the wicket rate — 7.74% of legal balls, a wicket every 13 balls or so, against about one in 22 in the powerplay. The death is where batters trade wickets for runs. The middle overs are where the singles live: the lowest dot rate, 28.4%.

⚠️ Common pitfall: filtering to legal balls silently drops some runs. The run rates above use legal balls only, so the runs from wides and no-balls — and anything hit off a no-ball — are not in the numerator. That is fine for a "what happens on a legal ball" question, and wrong for a "how many runs per over did teams score" question, where you should sum runs_total over all deliveries and divide by legal balls. Section 3.7 does it that way, and the two numbers differ. Always ask: which rows did my filter keep, and does my question need the others?

Several conditions at once: one bowler, one phase

jb = balls[(balls["bowler"] == "JJ Bumrah") & (balls["phase"] == "death")]
print(bowling_summary(jb)[["balls", "runs", "wickets", "economy", "dot_pct"]])
           balls  runs  wickets  economy  dot_pct
bowler                                           
JJ Bumrah   1423  1943      102     8.19    34.01

Jasprit Bumrah has bowled 1,423 legal balls at the death in the IPL and taken 102 wickets there at an economy of 8.19 — in the phase where, as the table above showed, the 2026 league as a whole went at over ten an over. We handed the filtered rows to the toolkit's bowling_summary(), which applies the book's standard bowling definitions. That pattern — filter first, then summarise — is how every leaderboard in the book is built.

.isin() is the tidy way to say "any of these values":

jb3 = balls[(balls["bowler"] == "JJ Bumrah") & balls["season"].isin(["2024", "2025", "2026"])]
print(bowling_summary(jb3, by=["bowler", "season"])[["balls", "runs", "wickets", "economy"]])
                  balls  runs  wickets  economy
bowler    season                               
JJ Bumrah 2024      311   336       20     6.48
          2025      284   316       18     6.68
          2026      294   410        4     8.37

Two seasons of the miserly Bumrah everyone knows, and then a 2026 in which, in the Cricsheet data, he took four wickets in 294 balls at 8.37 an over. The data tells you what; it cannot tell you why — conditions, role, fitness, the batters he met, plain variance over 49 overs. A 294-ball season is a small sample, a theme (Theme 3) that Chapter 6 makes rigorous. For now, notice how cheaply you found it: one filter, one summary.

Finally, .loc selects rows and columns in a single step — balls.loc[row_condition, list_of_columns]:

last3 = balls.loc[(balls["match_id"] == "1535465") & (balls["innings"] == 2),
                  ["over", "ball_in_over", "batter", "bowler", "runs_total"]].tail(3)
        over  ball_in_over     batter       bowler  runs_total
159131    18             4  JM Sharma  Arshad Khan           1
159132    18             5    V Kohli  Arshad Khan           4
159133    18             6    V Kohli  Arshad Khan           6

Those are the last three balls of the 2026 IPL final (match 1535465): a single, then Kohli four and six to finish the chase with two overs to spare. .tail(3) is .head()'s mirror image — the last three rows.

What happens on a ball, phase by phase

The script's last job is a chart. It labels each legal ball with an outcome (0, 1, 2, 4, 6, other, or wicket), uses groupby (next section) to get each outcome's share within each phase, and draws grouped bars:

Share of legal balls by outcome (%), IPL 2026:
outcome       0     1    2     4     6  other  wicket
phase                                                
powerplay  38.6  26.2  3.6  18.1   8.6    0.4     4.5
middle     24.9  45.4  6.1  11.3   7.5    0.1     4.6
death      23.5  37.7  6.9  13.2  10.7    0.2     7.7

Grouped bar chart of the share of legal balls ending in each outcome, by phase, IPL 2026

📊 Figure (described): For each outcome — dot, 1, 2, 4, 6, 3-or-5, wicket — three bars show the percentage of IPL 2026 legal balls in the powerplay (blue), middle overs (orange) and death (purple). The powerplay towers on dots (38.6%) and fours (18.1%); the middle overs on singles (45.4%); the death has the most sixes (10.7%) and wickets (7.7%). Three phases, three different games inside one innings.

(In this chart a ball on which a wicket fell is counted as "wicket" whatever else happened, which is why the dot shares are a little lower than the dot_pct column above, where a wicket ball with no run counted as a dot. Two defensible definitions, two slightly different numbers. Say which one you used.)

🔄 Check your understanding 1. Write the filter for "IPL deliveries bowled by Rashid Khan in the middle overs". 2. What is the difference between balls[balls["is_four"] | balls["is_six"]] and balls[balls["is_four"] & balls["is_six"]]? 3. The share of powerplay legal balls that were dots in 2026 was 41.4% in one table and 38.6% in another. Why?

Answer

  1. balls[(balls["bowler"] == "Rashid Khan") & (balls["phase"] == "middle")] — each condition in its own brackets, joined with &.
  2. | keeps balls that were a four or a six (all boundaries). & keeps balls that were a four and a six — none, so you get an empty DataFrame. Using the wrong one is a silent bug.
  3. The 41.4% counts any legal ball with zero runs_total as a dot, including wicket balls with no run. The 38.6% assigns wicket balls to a separate "wicket" category first. Same data, different definitions.

3.6 groupby: The Most Important Idea in This Chapter

The cricket question: Who scored the most runs in the 2026 IPL?

To answer that by hand you would take the season's 17,527 deliveries, sort them into piles — one pile per batter — add up the runs in each pile, and then sort the piles. pandas calls that three-step recipe split–apply–combine, and does it with one method, groupby:

b26 = balls[(balls["season"] == "2026") & ~balls["super_over"]]
runs_by_batter = b26.groupby("batter")["runs_batter"].sum()
print(runs_by_batter.sort_values(ascending=False).head(5))

Read it left to right: take the 2026 deliveries, split them into groups by batter, pick the runs_batter column, apply sum to each group, and combine the answers into one Series whose index is the batter's name.

type: Series  batters: 176
batter
V Suryavanshi      776
Shubman Gill       732
B Sai Sudharsan    722
V Kohli            675
H Klaasen          624

One hundred and seventy-six batters, and at the top Vaibhav Suryavanshi with 776 runs. If you understand that one line of code, you understand the idea behind most of the tables in this book. Every leaderboard, every phase profile, every season summary is a groupby.

📐 Definition: groupby splits a DataFrame's rows into groups that share a value (or a combination of values) in the key column(s), applies an aggregation (sum, mean, size, max…) to each group, and combines the results into a new table indexed by the key.

Several numbers at once: named aggregation

A leaderboard needs more than runs. .agg() computes several aggregations in one pass, each written as new_name=(column, function):

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"),
)
tbl["strike_rate"] = (100 * tbl["runs"] / tbl["balls"]).round(2)
top10 = tbl.sort_values("runs", ascending=False).head(10)

"size" counts rows (here, balls faced); summing the True/False is_four column counts fours. The new strike_rate column is computed for all 176 batters at once — no loop — because pandas divides column by column.

                 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
Ishan Kishan      602    330     60     32       182.42
KL Rahul          593    340     56     31       174.41
Abhishek Sharma   563    275     50     43       204.73
MR Marsh          563    345     51     36       163.19
JC Buttler        526    345     51     26       152.46

Horizontal bar chart of the ten leading run-scorers in IPL 2026, labelled with strike rates

📊 Figure (described): Ten horizontal bars, longest at the top: Suryavanshi 776, Gill 732, Sai Sudharsan 722, Kohli 675 and so on down to Buttler 526. Each bar is labelled with the batter's strike rate, which ranges from 152.46 (Buttler) to 237.31 (Suryavanshi). Total runs and the speed of scoring are different questions; the chart puts both on one page.

Look at the sixes column: Suryavanshi hit 72 sixes and 63 fours — more sixes than fours, over 327 balls. Gill, second on runs, hit 33 sixes off 449 balls. Two batters within 44 runs of each other, built completely differently. This is why a runs leaderboard alone is never the end of an analysis.

The toolkit already has a function that does all of this with the book's exact definitions — batting_summary() — and it is worth proving to yourself that your hand-built version agrees:

bs = batting_summary(b26)
same = (bs.loc[top10.index, "runs"] == top10["runs"]).all() and \
       (bs.loc[top10.index, "balls"] == top10["balls"]).all()
                 innings  runs  balls  outs  average  strike_rate
batter                                                           
V Suryavanshi         16   776    327    16    48.50       237.31
Shubman Gill          16   732    449    16    45.75       163.03
B Sai Sudharsan       17   722    457    16    45.12       157.99
V Kohli               16   675    407    12    56.25       165.85
H Klaasen             15   624    390    13    48.00       160.00
...
hand-built runs/balls identical to batting_summary: True

batting_summary adds innings, outs and the batting average (runs ÷ outs) — the last needs dismissal data, which is why the toolkit handles it. From here on you will mostly call the toolkit, but you now know there is no magic inside it: it is filters and groupbys like the ones you just wrote.

Leaderboards need minimums

Sort the same table by strike rate and the top is full of batters who faced a handful of balls — someone who hit his only ball for six has a strike rate of 600. Every serious leaderboard needs a minimum sample:

qual = bs[bs["balls"] >= 150].sort_values("strike_rate", ascending=False)
                 runs  balls  strike_rate  boundary_ball_pct
batter                                                      
V Suryavanshi     776    327       237.31              41.28
FH Allen          349    163       214.11              37.42
Priyansh Arya     364    172       211.63              34.30
Abhishek Sharma   563    275       204.73              33.82
RM Patidar        501    260       192.69              27.69
TH David          305    162       188.27              27.78
RD Rickelton      448    240       186.67              28.75
Ishan Kishan      602    330       182.42              27.88
batters with 150+ balls: 46

Forty-six batters faced 150 or more balls in the 2026 season. Suryavanshi found a boundary with 41.28% of the balls he faced. The cut-off of 150 is a judgement — high enough to keep out the cameos, low enough to keep the specialist finishers who rarely face many balls. Chapter 6 replaces this blunt cut-off with shrinkage, which uses every batter but trusts small samples less. For now: always state your minimum, and always show the balls column next to the rate.

The bowling version is one line:

                balls  runs  wickets  economy  average
bowler                                                
K Rabada          388   626       29     9.68    21.59
B Kumar           378   501       28     7.95    17.89
JC Archer         360   559       25     9.32    22.36
A Kamboj          302   530       21    10.53    25.24
Rashid Khan       341   516       21     9.08    24.57
E Malinga         326   507       20     9.33    25.35
Mohammed Siraj    372   562       19     9.06    29.58
Rasikh Salam      257   405       19     9.46    21.32

Kagiso Rabada took 29 wickets in IPL 2026, Bhuvneshwar Kumar 28 at a much better economy (7.95 against 9.68). Same pattern as Jamieson and Pandya in the final: the wickets column and the economy column rank bowlers differently.

🔄 Check your understanding 1. In b26.groupby("batter")["runs_batter"].sum(), what are the "split", the "apply" and the "combine"? 2. Why did we filter wides == 0 before the groupby that counts balls, rather than after? 3. Suryavanshi's 72 sixes came off 327 balls. Without code, roughly how often did he hit a six?

Answer

  1. Split: the 2026 deliveries are divided into one group per batter. Apply: sum adds the runs_batter values within each group. Combine: the 176 sums are stacked into one Series indexed by batter.
  2. Because "balls" is counted with size — the number of rows in each group. Once the rows are grouped and counted, the wides are already in the count; you must remove them first.
  3. About once every 4.5 balls (327 ÷ 72 ≈ 4.5).

Same code, different competition

Here is the payoff for writing code rather than reading tables: change one word and the analysis runs on a different competition. Swap "ipl" for "wpl" — the Women's Premier League:

w = load_deliveries("wpl")
wbs = batting_summary(w)
WPL deliveries: 20656  matches: 88  seasons: ['2022/23', '2023/24', '2024/25', '2025/26']
                 innings  runs  balls  outs  average  strike_rate
batter                                                           
NR Sciver-Brunt       36  1348    936    27    49.93       144.02
MM Lanning            35  1200    947    32    37.50       126.72
H Kaur                34  1193    820    26    45.88       145.49
Shafali Verma         37  1124    739    34    33.06       152.10
S Mandhana            35  1023    748    33    31.00       136.76
EA Perry              25   972    731    15    64.80       132.97
HK Matthews           34   867    711    33    26.27       121.94
GM Harris             30   818    547    27    30.30       149.54

                 balls  runs  wickets  economy
bowler                                        
AC Kerr            730   926       54     7.61
HK Matthews        680   863       46     7.61
S Ecclestone       762   873       43     6.87
NR Sciver-Brunt    714   960       40     8.07
M Kapp             798   804       38     6.05

Across four WPL seasons in the data, Nat Sciver-Brunt leads with 1,348 runs at 49.93, and also has 40 wickets — an all-rounder at the top of both tables. Ellyse Perry's average of 64.80 comes with only 15 dismissals in 25 innings. Amelia Kerr leads the wicket-takers with 54; Marizanne Kapp's economy of 6.05 is the lowest in the top five. Notice the season labels — '2022/23' for a league whose first edition was played in March 2023. Hold that thought until §3.8.

📋 Try it — Evaluate this player: Smriti Mandhana was the WPL's leading run-scorer in its 2025/26 season in the data. Using batting_summary(..., by=["batter", "season"]) on the WPL deliveries, build her season-by-season record. Was 2025/26 a step change or a continuation? Then use explore.phase_table (§Project Checkpoint) to compare her phase strike rates with Sciver-Brunt, Harmanpreet Kaur and Shafali Verma.

Worked answer

From code/07_try_it.py (the toolkit sorts by runs, so the seasons are out of calendar order):

text innings runs balls outs average strike_rate boundary_ball_pct season 2025/26 9 377 246 7 53.86 153.25 26.83 2023/24 10 300 224 10 30.00 133.93 22.32 2024/25 8 197 144 8 24.62 136.81 22.92 2022/23 8 149 134 8 18.62 111.19 18.66 career: 1023 runs, 748 balls, SR 136.76 phase SR, career: phase powerplay middle death batter S Mandhana 122.18 160.32 186.96 NR Sciver-Brunt 124.17 147.50 167.83 H Kaur 57.58 135.97 201.52 Shafali Verma 150.79 152.68 228.57

In calendar order her strike rate went 111.19 → 133.93 → 136.81 → 153.25, and her boundary-ball percentage rose every season from 18.66% to 26.83%. So 2025/26 was the steepest single step of a steady climb, not a bolt from the blue — though at 246 balls it is one season's sample, and Chapter 6 will show how much of a jump like that tends to persist. Her career phase profile is unusual for an opener: slower in the powerplay (122.18) than in the middle overs (160.32). Shafali Verma is the fastest of the four in every phase. Harmanpreet's 57.58 powerplay strike rate is the kind of number you must check the sample for before believing — she rarely bats in the powerplay — which is exactly what the next pitfall is about.

🔍 Why this works: why groupby beats a loop. You can compute every IPL batter's strike rate with a Python loop. The script times three ways of doing it over all 295,557 non-super-over IPL deliveries:

text rows scanned: 295,557 batters: 738 iterrows loop : 5.211 s zip loop : 0.085 s groupby : 0.048 s groupby vs iterrows: about 109x faster on this run Kohli SR, iterrows / zip / groupby: 134.8 134.8 134.8

All three get the same answer — Kohli's IPL career strike rate of 134.80 — but the beginner's favourite, iterrows(), which builds a Python object for every row, took over five seconds; groupby took a twentieth of a second, about 109 times faster on this run (your timings will differ by machine). The reason is where the work happens. A Python loop executes one Python instruction per row. groupby hands the whole column to compiled code inside pandas and NumPy that processes the numbers in a tight, optimised loop the Python interpreter never sees. For one season it hardly matters. When Chapter 20 fits a win-probability model to millions of deliveries across leagues, or Chapter 28 simulates thousands of tournaments, it is the difference between seconds and hours. Rule of thumb: if you are writing for row in over a DataFrame, there is almost always a vectorised way.

⚠️ Common pitfall: super overs. The same script reports Kohli SR if super-over balls are (wrongly) included: 134.86. A super over is a tie-breaker, not part of the match proper, and the book's batting and bowling tables leave super-over deliveries out (filter with ~balls["super_over"]). Here it moves Kohli's strike rate by six hundredths — small, but it means your number no longer matches anyone else's, and for a bowler who bowled a costly super over the effect can be much larger.


3.7 merge and pivot_table: Joining Tables, Reshaping Answers

The cricket question: How much has the average first-innings total in the IPL risen, season by season? And how do the 2026 leading run-scorers' strike rates change from phase to phase?

The first question needs information from two tables. Innings totals come from the deliveries (sum the runs per innings). Whether a match was shortened by rain (method = "D/L") or had no winner lives in the matches table — one row per match. To use both together we merge them on the column they share, match_id.

Step one: one row per innings, built with groupby on two keys. as_index=False keeps the keys as ordinary columns rather than turning them into the index:

inns = (balls[~balls["super_over"]]
        .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")))

(The brackets around the whole expression let a long chain of methods run over several lines.) Step two: the merge.

games["year"] = games["start_date"].dt.year
merged = inns.merge(games[["match_id", "year", "season", "result", "method", "winner"]],
                    on="match_id", how="left")
innings rows: 2480
after merge: (2480, 11)
  match_id  innings                 batting_team  runs  wickets  legal_balls  year season result method                  winner
0  1082591        1          Sunrisers Hyderabad   207        4          120  2017   2017    win   None     Sunrisers Hyderabad
1  1082591        2  Royal Challengers Bangalore   172       10          118  2017   2017    win   None     Sunrisers Hyderabad
2  1082592        1               Mumbai Indians   184        8          120  2017   2017    win   None  Rising Pune Supergiant
3  1082592        2       Rising Pune Supergiant   187        3          119  2017   2017    win   None  Rising Pune Supergiant

merge looked up each innings' match_id in the matches table and copied across the match's year, season, result, method and winner. how="left" means "keep every row of the left table (the innings), even if no match is found" — there should always be one here, and the row count (2,480 before and after) confirms nothing was lost or duplicated.

📐 Definition: merge (a join in database language) combines two tables by matching values in a key column. how="left" keeps all rows of the left table; "inner" keeps only rows with a match in both; "outer" keeps everything. If the key is not unique in the right-hand table, rows multiply — always compare row counts before and after.

Now the question. We keep first innings, in matches with a winner (dropping ties and no-results) and without a D/L revision:

first = merged[(merged["innings"] == 1) & merged["method"].isna() & merged["winner"].notna()]
by_season = first.groupby("season").agg(
    decided=("match_id", "nunique"),
    avg_1st_inns=("runs", "mean"),
    totals_200_plus=("runs", lambda s: int((s >= 200).sum())),
)

The lambda s: … is a tiny unnamed function — "given the runs of one season, s, count how many are at least 200". .isna() and .notna() test for missing values (§3.8).

         decided  avg_1st_inns  totals_200_plus
season                                         
2007/08       56         161.9                7
2009          53         150.3                1
2009/10       59         165.3                5
2011          69         155.6                4
2012          74         157.5                4
...
2021          59         159.3                6
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

You have just reproduced, from raw deliveries, the IPL scoring revolution that Chapter 1 opened with: an average first innings of 157.5 in 2012, 195.7 in 2026, and 37 first-innings totals of 200 or more in 2026 against four in 2012. The jump starts in 2023, the first season of the Impact Player rule (a named substitute who can bat and bowl). The data shows the jump; whether the rule caused it, and how much, is a harder question that later chapters treat carefully.

The merge also lets us ask whether the side batting first won. One comparison does it, because both columns are now in the same row:

merged["batting_side_won"] = merged["batting_team"] == merged["winner"]
IPL 2026, first-innings totals in matches with a winner:
                  size   mean  median
batting_side_won                     
False               45  183.2   181.0
True                27  217.0   216.0

In 2026, sides batting first won 27 of the 72 matches that had a winner (this count includes the season's one D/L-decided match). Their winning totals averaged 217.0; the totals that were chased down averaged 183.2.

📋 Try it — Settle this debate: "In the modern IPL, 200 batting first wins you the match." Using innings totals merged with match results (matches with a winner, no D/L), find, for each season since 2018, how many 200+ first-innings totals there were and what share were successfully defended. Then, for 2024–2026 combined, compare win rates for totals under 180, 180–199, 200–219 and 220+.

Worked answer

From code/07_try_it.py:

```text totals_200_plus defended win_pct year
2018 11 9 81.8 2019 8 7 87.5 2020 8 7 87.5 2021 6 5 83.3 2022 13 11 84.6 2023 23 16 69.6 2024 26 21 80.8 2025 32 24 75.0 2026 37 20 54.1 2008-2026: 212 totals of 200+, defended 161 (75.9%)

2024-2026, batting-first win % by first-innings total: size mean band
<180 77 0.130 180-199 39 0.487 200-219 47 0.617 220+ 48 0.750 ```

Across the whole history, 200 batting first has been defended 75.9% of the time. In 2026 it was defended only 20 times out of 37 — 54.1%, barely better than a coin. The debate is settled, in this data, against the old rule of thumb: in 2024–2026, 200–219 won 61.7% of the time and even 220+ lost a quarter of the time. Under 180 batting first, sides won only 13%. The bar has moved; any model that hard-codes "200 is a winning score" was calibrated to a different sport. (These are small yearly samples — 37 totals in 2026 — so treat the year-to-year wiggles with care.)

Run rate by season and phase

The deliveries table already carries each match's season and start_date (the toolkit merged them in when it built the file), so a run-rate-by-phase-by-year table is a groupby on two keys followed by .unstack(), which turns the inner key (phase) into columns:

nb = balls[~balls["super_over"]].copy()
nb["year"] = nb["start_date"].dt.year
rr = nb.groupby(["year", "phase"]).agg(runs=("runs_total", "sum"), legal=("is_legal", "sum"))
rr["run_rate"] = (6 * rr["runs"] / rr["legal"]).round(2)
rr_wide = rr["run_rate"].unstack()[["powerplay", "middle", "death"]]

This time runs_total is summed over all deliveries, wides and no-balls included, and divided by legal balls — the way a scoreboard computes run rate.

phase  powerplay  middle  death
year                           
2008        7.70    7.99   9.95
...
2022        7.82    8.08  10.45
2023        8.72    8.43  10.49
2024        9.47    8.83  11.21
2025        9.61    9.03  10.96
2026       10.10    9.31  10.79

Line chart of IPL run rate per over in the powerplay, middle and death phases, 2008 to 2026

📊 Figure (described): Three lines — powerplay, middle and death run rates — from 2008 to 2026, with a dashed marker at 2023. For fifteen years the powerplay and middle overs ran at 7–8.5 an over and the death at 9–10.5. After 2023 the powerplay line shoots up to 10.10 in 2026, almost touching the death line (10.79), which has actually dipped since its 2024 peak of 11.21. The modern IPL is scoring its extra runs at the start of the innings.

Compare that 2026 death figure — 10.79, using all runs — with the 10.32 from §3.5, which used legal balls only. The difference is wides, no-balls and runs hit off no-balls. Both numbers are correct answers to slightly different questions.

pivot_table: reshaping into a grid

The second question — each top run-scorer's strike rate in each phase — wants a grid: batters down the side, phases across the top. pivot_table builds it in one call, with index (rows), columns, values and aggfunc:

names = list(top10.index)
sub = faced[faced["batter"].isin(names)]
piv_runs = sub.pivot_table(index="batter", columns="phase", values="runs_batter", aggfunc="sum")
piv_balls = sub.pivot_table(index="batter", columns="phase", values="runs_batter", aggfunc="size")
piv_sr = (100 * piv_runs / piv_balls).round(1)

Dividing one grid by another works cell by cell, because pandas lines the two up by their row and column labels.

strike rate:
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
KL Rahul             150.6   189.3  226.7
Abhishek Sharma      214.5   202.3  117.6
MR Marsh             170.7   155.6  145.5
JC Buttler           162.1   143.4  170.5

balls faced (the sample behind each cell):
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
KL Rahul               160     150     30
Abhishek Sharma        172      86     17
MR Marsh               188     135     22
JC Buttler             103     198     44

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

📊 Figure (described): A ten-by-three grid, colour-coded from dark purple (low strike rate) to yellow (high). Suryavanshi's row is bright all the way across, peaking at 290 in the death — off only 10 balls. Klaasen's powerplay cell is the darkest (100, off 21 balls); his real work is in the middle (265 balls) and death (104). Each cell shows its balls faced, so a bright cell built on ten balls can be told apart from one built on two hundred.

The heat map is a lesson in reading a grid honestly. The balls table matters as much as the strike-rate table. Kohli's death strike rate of 244.4 is from 27 balls; Suryavanshi's 290.0 from 10; Abhishek Sharma's 117.6 from 17. Those cells are a handful of overs each — enough to describe what happened, nowhere near enough to say what will happen. Klaasen, by contrast, faced 104 death balls in a single season, more than four times as many as any other top-ten batter here: his role as a finisher is visible in the balls grid before you even look at the rates. Theme 2 of this book — that the phases of a T20 innings are different games — and Theme 3 — that small samples lie — are both sitting in this one picture. Chapter 8 builds full phase profiles; Chapter 6 shows how to put error bars on cells like these.

🔷 R corner (not run in this book's build): the same top-ten table in R with dplyr and arrow, reading the same Parquet file.

r library(dplyr) library(arrow) balls <- read_parquet("data/processed/ipl_deliveries.parquet") balls |> filter(season == "2026", wides == 0, !super_over) |> group_by(batter) |> summarise(runs = sum(runs_batter), balls = n(), fours = sum(is_four), sixes = sum(is_six)) |> mutate(strike_rate = round(100 * runs / balls, 2)) |> arrange(desc(runs)) |> head(10)

group_by() + summarise() is R's split–apply–combine; filter, mutate and arrange are pandas' boolean mask, new column and sort_values. Appendix J has more.

🔄 Check your understanding 1. You merge a table of 2,480 innings with the matches table and get 2,491 rows. What has probably gone wrong? 2. Why did we use aggfunc="size" for the balls grid but aggfunc="sum" for the runs grid? 3. Klaasen's 2026 powerplay strike rate was 100.0. Write one sentence a careful analyst would add before quoting it.

Answer

  1. Some match_id appears more than once in the right-hand table, so those innings were matched twice and duplicated. Check with games["match_id"].is_unique before merging.
  2. Balls faced is a count of rows (one row per ball) — size. Runs is the total of a column — sum. Summing runs_batter for the balls grid would give runs, not balls.
  3. "That figure comes from only 21 balls, about three and a half overs across a whole season, so it says little about his powerplay ability — he mostly batted later."

3.8 Missing Values, Messy Labels and Dates

The cricket question: Why does games[games["season"] == 2026] return nothing at all?

Real data is untidy, and cricket data has its own particular untidiness. Three kinds matter in your first week.

Labels that are not what they seem

dtype of season: object
distinct seasons: ['2007/08', '2009', '2009/10', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020/21', '2021', '2022', '2023', '2024', '2025', '2026']
games[games.season == 2026] rows  : 0
games[games.season == '2026'] rows: 74

The season column is text (pandas calls its type object), not a number. The number 2026 and the string "2026" are different things, so the first filter matches nothing — and raises no error. Worse, some IPL seasons are labelled with two years. Cricsheet uses the cricket-season convention of the source, and the IPL's 2008 season is stored as '2007/08', its 2010 season as '2009/10', and its 2020 season as '2020/21'. The WPL's first season (played in 2023) is '2022/23'; the 2025 Women's World Cup is '2025/26'.

The fix is to create a numeric year from the match date, which is unambiguous:

games["year"] = games["start_date"].dt.year
          min   max  size
season                   
2007/08  2008  2008    58
2009     2009  2009    57
2009/10  2010  2010    60
2011     2011  2011    73

⚠️ Common pitfall: the season is text, and not always a year. Filter on season with a string (== "2026"), or better, build a year column from start_date and filter on that. Searching for the 2020 IPL with season == "2020" returns zero rows, silently, because it is stored as "2020/21". The toolkit's convention — and the project module's season_year() function — is to use the start date's calendar year wherever a number is needed.

Team names change too. From code/07_try_it.py:

distinct team names: 19
                             first_year  last_year
team                                              
Delhi Capitals                     2019       2026
Delhi Daredevils                   2008       2018
Kings XI Punjab                    2008       2020
Punjab Kings                       2021       2026
Royal Challengers Bangalore        2008       2023
Royal Challengers Bengaluru        2024       2026

The franchise that won the 2025 final appears in the data under two names — "Bangalore" until 2023, "Bengaluru" from 2024. Ask for "Royal Challengers Bengaluru"'s all-time record and you will get three seasons, not nineteen. Whenever you analyse a team across seasons, check the name list first and map old names to new ones explicitly.

Missing values: what does "nothing" mean?

pandas marks a missing value as NaN (for numbers) or None (for text), and .isna().sum() counts them per column:

deliveries columns with missing values:
legal_ball_index     11102
wicket_kind         281027
player_out          281027
fielders            281027
target_runs         153429
target_overs        153429
share of deliveries with no wicket_kind: 95.03 %
wides + no-balls (legal_ball_index missing): 11102 = 11102
rows with target_runs present -> innings: [np.int64(2)]

None of these are errors. Each "missing" means something specific:

  • wicket_kind is empty on 95.03% of deliveries because no wicket fell on them. Missing means "not applicable", not "unknown".
  • legal_ball_index (the count of legal balls so far in the innings) is empty on exactly the 11,102 wides and no-balls, because those deliveries do not count as balls of the over.
  • target_runs is filled only in the second innings — there is no target until someone has batted.

The matches table:

matches columns with missing values:
match_number        74
stage             1169
city                51
winner              25
win_by_runs        685
win_by_wickets     583
method            1220
eliminator        1227

why is 'winner' missing?
result
tie          16
no result     9

venues whose city is missing (top 3):
venue
Dubai International Cricket Stadium    33
Sharjah Cricket Stadium                18

winner is missing for 25 matches: 16 ties (in the IPL these were decided by super overs, recorded separately in eliminator) and nine no-results. stage is missing for 1,169 matches because league games have no stage — only playoffs do. method is missing for 1,220 matches because they were not rain-affected; the 23 that were are marked "D/L". win_by_runs is missing whenever the side batting second won (by wickets instead). And city is missing for 51 matches — all 51 at Dubai (33) and Sharjah (18), where the source simply did not record a city. That one is a genuine gap in the data.

Two tools handle missing values:

games["method"].fillna("normal").value_counts()   # fill for display
games["win_by_runs"].mean()                       # NaN skipped by default
method
normal    1220
D/L         23
mean of win_by_runs, NaN skipped by default: 31.04  from 558 matches

fillna(value) replaces missing values; dropna() removes rows that have them. And most pandas calculations skip NaN by default — the average winning margin by runs, 31.04, is over the 558 matches won by the side batting first, not all 1,243. Usually that is what you want. Occasionally it hides a problem. Know that it is happening.

Dates

start_date is stored as a proper date-time type (datetime64), which means pandas can do arithmetic on it and pull out parts with the .dt accessor:

games["month"] = games["start_date"].dt.month
games["weekday"] = games["start_date"].dt.day_name()
span = games.groupby("season")["start_date"].agg(["min", "max"])
span["days"] = (span["max"] - span["min"]).dt.days
first IPL match in the data: 2008-04-18 | last: 2026-05-31
              min        max  days
season                            
2023   2023-03-31 2023-05-29    59
2024   2024-03-22 2024-05-26    65
2025   2025-03-22 2025-06-03    73
2026   2026-03-28 2026-05-31    64

matches by weekday:
weekday
Sunday       273
Saturday     231
Friday       156
Wednesday    156
Tuesday      153
Thursday     143
Monday       131

seasons played (partly) outside April-June:
season
2020/21    [9, 10, 11]
2021           [9, 10]

Subtracting two dates gives a duration, and .dt.days turns it into a number: the 2025 season ran 73 days from first match to final, the longest of the last four. Sundays (273 matches) and Saturdays (231) host the most games — double-headers. And the month filter finds the two seasons that broke the April–June pattern: the 2020 season, played in September to November, and the second half of the 2021 season, played in September and October. (Both were moved to the UAE during the COVID-19 pandemic — public, well-documented history, and the reason Dubai and Sharjah appear so often in the venue list.)

Heat map of IPL matches by year and calendar month, 2008 to 2026

📊 Figure (described): A grid of years (rows, 2008–2026) by months (columns, January–December), each cell showing how many IPL matches started that month. Almost every row is lit only in March–June. Two rows break the pattern: 2020, lit in September–November, and 2021, split between April–May and September–October. A pivot_table on two .dt columns turns a date column into the league's calendar history.

🔄 Check your understanding 1. You want every IPL match played in 2010. Write a filter that will not silently fail. 2. wicket_kind is missing on 95% of deliveries. Should you dropna() those rows before computing strike rates? 3. Why is win_by_runs missing for about half the matches?

Answer

  1. games[games["start_date"].dt.year == 2010] — or games["season"] == "2009/10", if you know the label. The date version cannot be fooled by labels.
  2. No! You would throw away every delivery on which no wicket fell — 95% of the data — and compute strike rates from dismissal balls only. Missing here means "no wicket", which is information.
  3. Margins are expressed in runs when the side batting first wins and in wickets when the chasing side wins, so each match has a value in only one of the two columns (and neither for ties and no-results).

3.9 When It Breaks: Reading a Traceback

The cricket question: Your code has stopped with a wall of red text. What is it telling you?

Every programmer, at every level, spends a large part of their time reading error messages. Python's error report is called a traceback, and the single most useful skill for a beginner is to read it from the bottom up. The last line says what went wrong; the lines above it say where, innermost call last.

code/05_errors_and_tracebacks.py makes the common mistakes on purpose and catches them, so you can see each one in a safe place. Here is a full traceback (file paths shortened):

Traceback (most recent call last):
  File "...\code\05_errors_and_tracebacks.py", line 33, in show
    result = fn()
  File "...\code\05_errors_and_tracebacks.py", line 50, in <lambda>
    lambda: scorecard_line("V Kohli", 43, 35), full=True)
            ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
  File "...\code\05_errors_and_tracebacks.py", line 46, in scorecard_line
    return name + " scored " + runs + " off " + str(balls_faced)
           ~~~~~~~~~~~~~~~~~~^~~~~~
TypeError: can only concatenate str (not "int") to str

Bottom line first: TypeError: can only concatenate str (not "int") to str. You tried to glue a number onto text with +. One line up: the exact code, with ^^^ markers under the offending + runs. Above that, the chain of calls that led there. The fix: str(runs), or better, an f-string.

The rest, by last line only:

NameError: name 'kohli_run' is not defined. Did you mean: 'kohli_runs'?
ZeroDivisionError: division by zero
KeyError: 'Batter'
AttributeError: 'DataFrame' object has no attribute 'Phase'. Did you mean: 'phase'?
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
TypeError: Cannot perform 'rand_' with a dtyped [object] array and scalar of type [bool]
FileNotFoundError: [Errno 2] No such file or directory: 'data/processed/IPL_deliveries.parquet'
IndexError: list index out of range
Error What you did Fix
NameError used a name that doesn't exist (a typo) read the "Did you mean" hint
ZeroDivisionError divided by zero — a batter with 0 balls guard with if balls == 0 (§3.3)
KeyError: 'Batter' asked for a column that doesn't exist — names are case-sensitive print(balls.columns) and copy the exact name
AttributeError … 'Phase' same mistake with dot-access use balls["phase"]
ValueError: truth value … ambiguous used Python's and / or between two Series use & / \| with brackets around each condition
TypeError: Cannot perform 'rand_' forgot the brackets: balls["phase"] == "death" & … (balls["phase"] == "death") & (…) — & binds tighter than ==
FileNotFoundError wrong path or wrong capitals (IPL_ vs ipl_) use the toolkit's loaders rather than typing paths
IndexError asked for last_over[6] — positions run 0 to 5 remember counting starts at 0

The "missing brackets" error deserves a sentence. In balls["phase"] == "death" & balls["season"] == "2026", Python does the & first, trying to compute "death" & balls["season"], which is nonsense — hence the baffling message. Brackets around every condition, always.

The bugs that don't crash

Errors that crash are the friendly kind: you know something is wrong. The dangerous ones run perfectly and give you the wrong answer:

10. games[games['season'] == 2026] -> 0 rows
    games[games['season'] == '2026'] -> 74 rows
    games[games['season'] == '2020'] -> 0 rows (the 2020 season is stored as '2020/21')

11. Kohli IPL balls, wides included : 7123  SR 131.07
    Kohli IPL balls, wides excluded : 6926  SR 134.8

12. assigning a new column to a filtered slice -> warnings raised: ['SettingWithCopyWarning']
    with .copy() first: no warning; big-hit death balls = 5508

Number 11 is the classic. Count every row with Kohli on strike as a "ball faced" and you include 197 wides; his career strike rate comes out at 131.07 instead of the correct 134.80. No error, plausible number, wrong.

Number 12 is pandas warning you that you filtered a table and then tried to add a column to the result, and that it is not sure whether you meant to change the original. Add .copy() when you filter a table you intend to modify — death = balls[balls["phase"] == "death"].copy() — and the ambiguity disappears. (In pandas 3, where "copy-on-write" behaviour is the default, the warning no longer appears and a filtered table always behaves as an independent copy; the .copy() is still the clearest way to say what you mean, and works in every version.)

⚠️ Common pitfall: a result with zero rows is not an answer. Whenever a filter returns an empty DataFrame, assume a bug before you assume a fact. Check len(result) after every important filter, and print a few rows. "Nobody scored a run in the 2020 IPL" is not a finding.

🔄 Check your understanding 1. A traceback ends KeyError: 'Runs_batter'. What do you check first? 2. balls[balls["over"] > 15 and balls["season"] == "2026"] crashes. Rewrite it. 3. Which is more dangerous, a KeyError or counting wides as balls faced? Why?

Answer

  1. The exact column name: print(balls.columns). Column names are case-sensitive; the real one is runs_batter.
  2. balls[(balls["over"] > 15) & (balls["season"] == "2026")] — & instead of and, brackets around each condition.
  3. Counting wides. A KeyError stops you immediately; the wides bug runs perfectly and produces a plausible wrong number (131.07 instead of 134.80 for Kohli) that you might publish.

3.10 Putting It Together: The 2025 Final, Rebuilt from 252 Deliveries

The cricket question: Can we rebuild the complete scorecard of the IPL 2025 final — batting, bowling, extras, fall of wickets, the over-by-over story — from nothing but ball-by-ball rows?

Everything in this chapter so far has been a tool. Now we use them all at once. code/06_scorecard.py does it in steps, and every step is a filter, a groupby, a sort, or a merge.

Step 0 — find the match. Filter the matches table for finals, then pick the 2025 one:

finals = games[games["stage"] == "Final"]
MID = finals.loc[finals["season"] == "2025", "match_id"].iloc[0]
fin = balls[balls["match_id"] == MID]
match id: 1473511 | Narendra Modi Stadium, Ahmedabad | 2025-06-03 | toss: Punjab Kings chose to field
deliveries in the match: 252  legal: 240

.iloc[0] means "the first item by position" (where .loc is by label). 252 deliveries, 240 of them legal — two complete 20-over innings plus twelve wides.

Step 1 — innings totals. A groupby on innings:

tot = fin.groupby("innings").agg(team=("batting_team", "first"), runs=("runs_total", "sum"),
                                 wickets=("is_wicket", "sum"), legal=("is_legal", "sum"),
                                 extras=("runs_extras", "sum"))
                                team  runs  wickets  legal  extras
innings                                                           
1        Royal Challengers Bengaluru   190        9    120       9
2                       Punjab Kings   184        7    120      11

Step 2 — the batting card. Three pieces: runs and balls per batter (a groupby on balls faced), the order they came in, and how they were out.

inn1 = fin[fin["innings"] == 1].sort_values("delivery_seq")
faced = inn1[inn1["wides"] == 0]
bat = faced.groupby("batter").agg(R=("runs_batter", "sum"), B=("runs_batter", "size"),
                                  fours=("is_four", "sum"), sixes=("is_six", "sum"))
order = []
for s, ns in zip(inn1["batter"], inn1["non_striker"]):
    for name in (s, ns):
        if name not in order:
            order.append(name)
bat = bat.reindex(order)
outs = inn1[inn1["is_wicket"]].set_index("player_out")[["wicket_kind", "bowler", "fielders"]]
bat = bat.join(outs)
bat["wicket_kind"] = bat["wicket_kind"].fillna("not out")

The batting order is not stored anywhere in Cricsheet, so we infer it: walk through the deliveries in order and note each name the first time it appears at either end. That is a loop — and a legitimate one, because it runs over 126 deliveries, not 295,732, and the logic ("first time I see this name") is naturally sequential. .reindex(order) then puts the batting table in that order. .join() is a merge on the index: it attaches each batter's dismissal row, and the batter who was never dismissed gets missing values, which fillna("not out") turns into the right words.

                 R   B  fours  sixes     SR        wicket_kind              bowler        fielders
batter                                                                                            
PD Salt         16   9      2      1  177.8             caught         KA Jamieson         SS Iyer
V Kohli         43  35      3      0  122.9  caught and bowled  Azmatullah Omarzai                
MA Agarwal      24  18      2      1  133.3             caught           YS Chahal  Arshdeep Singh
RM Patidar      26  16      1      2  162.5                lbw         KA Jamieson                
LS Livingstone  25  15      0      2  166.7                lbw         KA Jamieson                
JM Sharma       24  10      2      2  240.0             bowled   Vijaykumar Vyshak                
R Shepherd      17   9      1      1  188.9                lbw      Arshdeep Singh                
KH Pandya        4   5      0      0   80.0             caught      Arshdeep Singh         SS Iyer
B Kumar          1   2      0      0   50.0             caught      Arshdeep Singh   Priyansh Arya
Yash Dayal       1   1      0      0  100.0            not out                 NaN             NaN

Step 3 — the bowling card, using the toolkit's runs_conceded() and bowler_wicket() helpers so that byes and leg-byes are not charged to the bowler and run-outs are not credited to him:

                    O   R  W   Econ  wides
bowler                                    
Arshdeep Singh      4  40  3  10.00      2
KA Jamieson         4  48  3  12.00      3
Azmatullah Omarzai  4  35  1   8.75      2
Vijaykumar Vyshak   4  30  1   7.50      2
YS Chahal           4  37  1   9.25      0
bowlers' runs + byes + leg-byes = 190 | team total = 190

The last line is a reconciliation check: the bowlers' runs plus byes and leg-byes must equal the team total. They do. Build checks like this into everything you write; they catch definition errors that no traceback ever will.

Step 4 — both innings at once. The project module for this chapter, explore.py (see the Project Checkpoint below), packages Steps 1–3 plus the fall of wickets into one function, format_scorecard():

Royal Challengers Bengaluru v Punjab Kings - Indian Premier League Final
Narendra Modi Stadium, Ahmedabad, 2025-06-03

Royal Challengers Bengaluru  190/9 (20 ov)
  PD Salt             c SS Iyer b KA Jamieson             16    9   2   1   177.8
  V Kohli             c & b Azmatullah Omarzai            43   35   3   0   122.9
  MA Agarwal          c Arshdeep Singh b YS Chahal        24   18   2   1   133.3
  RM Patidar          lbw b KA Jamieson                   26   16   1   2   162.5
  LS Livingstone      lbw b KA Jamieson                   25   15   0   2   166.7
  JM Sharma           b Vijaykumar Vyshak                 24   10   2   2   240.0
  R Shepherd          lbw b Arshdeep Singh                17    9   1   1   188.9
  KH Pandya           c SS Iyer b Arshdeep Singh           4    5   0   0    80.0
  B Kumar             c Priyansh Arya b Arshdeep Singh     1    2   0   0    50.0
  Yash Dayal          not out                              1    1   0   0   100.0
  Extras 9 (w 9, nb 0, b 0, lb 0, pen 0)
  FoW: 1-18 (PD Salt, 1.4), 2-56 (MA Agarwal, 6.2), 3-96 (RM Patidar, 10.5), 4-131 (V Kohli, 14.5), 5-167 (LS Livingstone, 16.5), 6-171 (JM Sharma, 17.4), 7-188 (R Shepherd, 19.2), 8-189 (KH Pandya, 19.4), 9-190 (B Kumar, 19.6)
  Bowling                 O  M    R  W   Econ
  Arshdeep Singh          4  0   40  3  10.00
  KA Jamieson             4  0   48  3  12.00
  Azmatullah Omarzai      4  0   35  1   8.75
  Vijaykumar Vyshak       4  0   30  1   7.50
  YS Chahal               4  0   37  1   9.25

Punjab Kings  184/7 (20 ov)
  Priyansh Arya       c PD Salt b JR Hazlewood            24   19   4   0   126.3
  P Simran Singh      c B Kumar b KH Pandya               26   22   0   2   118.2
  JP Inglis           c LS Livingstone b KH Pandya        39   23   1   4   169.6
  SS Iyer             c JM Sharma b R Shepherd             1    2   0   0    50.0
  N Wadhera           c KH Pandya b B Kumar               15   18   0   1    83.3
  Shashank Singh      not out                             61   30   3   6   203.3
  MP Stoinis          c Yash Dayal b B Kumar               6    2   0   1   300.0
  Azmatullah Omarzai  c MS Bhandage b Yash Dayal           1    2   0   0    50.0
  KA Jamieson         not out                              0    2   0   0     0.0
  Extras 11 (w 3, nb 0, b 0, lb 8, pen 0)
  FoW: 1-43 (Priyansh Arya, 4.6), 2-72 (P Simran Singh, 8.3), 3-79 (SS Iyer, 9.4), 4-98 (JP Inglis, 12.1), 5-136 (N Wadhera, 16.2), 6-142 (MP Stoinis, 16.4), 7-145 (Azmatullah Omarzai, 17.2)
  Bowling                 O  M    R  W   Econ
  B Kumar                 4  0   38  2   9.50
  Yash Dayal              3  0   18  1   6.00
  JR Hazlewood            4  0   54  1  13.50
  KH Pandya               4  0   17  2   4.25
  Suyash Sharma           2  0   19  0   9.50
  R Shepherd              3  0   30  1  10.00

Result: Royal Challengers Bengaluru won by 6 runs
Player of the match: KH Pandya

That is a newspaper scorecard, built from 252 rows. Read it as a cricketer and the story is all there. RCB never got away — no fifty, their top score Kohli's 43 — and lost three wickets for three runs in the last over to Arshdeep Singh (the fall of wickets: 7-188, 8-189, 9-190, all in the 20th over). Punjab's chase stalled in the middle: from 72 for 1 in the 9th over they lost Prabhsimran Singh, Shreyas Iyer and Josh Inglis for 26 runs, with Krunal Pandya's four overs going for 17. When Nehal Wadhera and Marcus Stoinis fell in the 17th over, they were 142 for 6. Shashank's 61 not out off 30 came too late.

The fall-of-wickets notation uses cricket's convention, not a decimal: 14.5 means "the fifth ball of the fifteenth over" (14 overs completed plus 5 balls). The function computes it from the 1-based over column as over − 1 and ball_in_over. One more detail a real scorecard shows: Omarzai was caught by MS Bhandage, who did not bat or bowl. Cricsheet's raw JSON file for this match marks that fielder with "substitute": true, and also records both sides' Impact Player swaps (Prabhsimran Singh in for Yuzvendra Chahal, Suyash Sharma in for Mayank Agarwal); the toolkit's flattened table keeps only the fielder's name. Every flattening throws something away — when a detail matters, go back to the raw file, as Chapter 2 showed.

Step 5 — over by over. explore.over_by_over() is a groupby on ["innings", "over"] with a running total added by .cumsum() within each innings. A pivot_table lays the two innings side by side:

        runs     wickets   
innings    1   2       1  2
over                       
...
15         7  13       1  0
16        13  17       0  0
17        23   8       1  2
18         5   5       1  1
19        14  13       0  0
20         3  22       3  0
after 10 overs PBKS 81/3: need 110 off 60
after 15 overs PBKS 119/4: need 72 off 30
after 16 overs PBKS 136/4: need 55 off 24
after 17 overs PBKS 144/6: need 47 off 18
after 18 overs PBKS 149/7: need 42 off 12
after 19 overs PBKS 162/7: need 29 off 6

Bar chart of runs in each over of both innings of the IPL 2025 final, with wickets marked as circles

📊 Figure (described): Paired bars for each of the 20 overs — red for RCB batting first, blue for Punjab chasing — with an open circle above a bar for each wicket in that over. RCB's 17th over (23 runs) is their tallest bar, followed immediately by three wickets in their 20th over, which went for only 3. Punjab's tallest bars are the 16th (17) and the final over (22), but the two-wicket 17th over (8 runs) sits between them. A first, simple version of the "Manhattan" chart that Chapter 7 builds properly.

Cumulative runs for both innings of the IPL 2025 final, with the target line at 191

📊 Figure (described): Two lines of cumulative runs by overs completed — the "worm". RCB's red line finishes at 190/9; Punjab's blue line tracks just below it for most of the chase, falls further behind through overs 12–18, and then climbs steeply in the last over to finish at 184/7, short of the dotted target line at 191. The gap between the lines at any over is how far the chase was behind at that point.

The chase table tells you something the scorecard alone does not. After 16 overs Punjab needed 55 off 24 with six wickets in hand. After 17 they needed 47 off 18 with four in hand — Bhuvneshwar Kumar's two-wicket 17th over, for eight runs, changed the equation more than any other over in the innings. How much more, in probability terms, is what Chapter 9 and Chapter 20 will measure with a win-probability model built from thousands of chases like this one.

🏏 Eye test: Wendell Baptiste, who coached seamers for longer than Nusrat has been alive, looked at her rebuilt scorecard over a video call.

Wendell: Good. Now tell me where Krunal bowled.

Nusrat: It says 4–0–17–2.

Wendell: That's what happened. I asked where. Pace off? Into the pitch? Wide of off stump with the long boundary on that side? Your 252 rows don't know. Neither do they know who dropped what, which fielder cut off the boundary that would've been four, or whether the bowler at the other end was carrying a sore side.

Nusrat: So the scorecard is useless?

Wendell: No. It's complete about the things it records, which is more than my memory is. It tells me which overs to go and watch again. The 17th over in the chase — two wickets for eight — I'd want to see that. Your numbers tell me where to point my eyes.

He is right on both counts. Cricsheet's ball-by-ball data has no line, length, pace, field placements, drops or misfields (Chapter 2 lists what it lacks). The rebuilt scorecard is a perfect record of outcomes and a blank page on causes. The analyst's job is to use the first to direct attention to the second.

📋 Try it — Analyze this match: Run explore.format_scorecard() on the 2026 IPL final (Gujarat Titans v Royal Challengers Bengaluru, 31 May 2026; find its id with explore.find_matches(games, season="2026", stage="Final")). Where did the side batting first fall short, and how did the chase unfold?

Worked answer

From code/project_checkpoint.py (abridged):

text Gujarat Titans 155/8 (20 ov) B Sai Sudharsan c JM Sharma b B Kumar 12 12 2 0 100.0 Shubman Gill c RM Patidar b JR Hazlewood 10 8 2 0 125.0 N Sindhu c D Padikkal b Rasikh Salam 20 18 3 0 111.1 JC Buttler st JM Sharma b KH Pandya 19 23 1 0 82.6 Washington Sundar not out 50 37 5 0 135.1 ... FoW: 1-22 (Shubman Gill, 2.2), 2-26 (B Sai Sudharsan, 3.4), 3-55 (N Sindhu, 7.6), 4-73 (JC Buttler, 12.1), ... Royal Challengers Bengaluru 161/5 (18 ov) VR Iyer c K Rabada b Mohammed Siraj 32 16 4 2 200.0 V Kohli not out 75 42 9 3 178.6 ... Result: Royal Challengers Bengaluru won by 5 wickets Player of the match: V Kohli

Gujarat lost their two leading run-scorers of the season — Gill (732 runs in the 2026 season) and Sai Sudharsan (722) — inside four overs, 26 for 2, and Buttler's 19 off 23 left them 73 for 4 after 12.1 overs. Washington Sundar's unbeaten 50 got them to 155 for 8 — 40.7 runs below that season's average decided first-innings total of 195.7. RCB raced to 62 without loss in under five overs (Venkatesh Iyer 32 off 16) and Kohli's 75 not out off 42 finished it with two overs to spare. In a season of 200s, 155 was always going to be short; the data puts a number on "always".

🔄 Check your understanding 1. Cricsheet does not store batting positions. How did we recover the batting order? 2. What does 14.5 mean in a fall-of-wickets list, and how is it computed from the toolkit's columns? 3. Name the reconciliation check in Step 3, and one other check you could add.

Answer

  1. By walking through the innings' deliveries in order and recording each name the first time it appears as striker or non-striker.
  2. The fifth ball of the 15th over (14 complete overs plus 5 balls). It is over − 1 (the toolkit's over is 1-based) followed by ball_in_over.
  3. Bowlers' runs + byes + leg-byes = team total. Others: the batters' runs plus all extras equal the total; the batting card's dismissals equal the wickets in the total; the sum of over_by_over runs equals the total.

Spaced Review

Before we package the chapter's code into the project, three questions from earlier chapters. Try each before you open the answer.

  1. (From Chapter 1.) Kohli's IPL career strike rate is 134.80 and Suryakumar Yadav's is 148.59 (book data, through the 2026 season). Using only what you learned in this chapter, how would you check which of them scores faster at the death? What filter and what summary?
  2. (From Chapter 2.) The toolkit turns Cricsheet's files into two tables. What does one row of each represent, and which column links them?
  3. (From Chapter 2.) Name two things that a ball-by-ball file does not record, and say which section of this chapter ran into one of them.
Answer
  1. Filter the IPL deliveries to phase == "death" and to the two batters (balls["batter"].isin(["V Kohli", "SA Yadav"])), then call batting_summary() — or call explore.phase_table(balls, ["V Kohli", "SA Yadav"]), which the Project Checkpoint shows returns 188.38 for Kohli and 178.21 for Suryakumar in the death. Kohli is faster at the death; Suryakumar's overall edge comes from the middle overs (144.14 against 125.80). This is the story Chapter 1 told — and you can now verify it yourself in one line.
  2. deliveries: one row per delivery bowled (legal or not). matches: one row per match. They link on match_id — the key we used to merge in §3.7.
  3. For example: batting positions (we had to infer the batting order in §3.10), line and length, shot direction, fielding positions, dropped catches, ball speed. Wendell's eye test in §3.10 is a list of exactly these gaps.

Project Checkpoint: explore.py

Nusrat's project, Crease, got its first real module this chapter. Chapter 2 built the data layer; project/crease/explore.py is the first thing a fan looks at: a scorecard for any match, an over-by-over table, leaderboards and season summaries — for any competition in the data, men's or women's, with one function call each.

The module's public functions:

Function What it returns
season_year(matches) a numeric calendar year per match (the fix for §3.8's season-label trap)
find_matches(matches, team=, season=, stage=, year=) the filtered match table
batting_order(balls, match_id, innings) batters in the order they came in (inferred)
batting_card(...), bowling_card(...) one innings' cards, with dismissal text, maidens, economy
innings_total(...), fall_of_wickets(...) runs/wickets/overs/extras; score at each wicket
over_by_over(balls, match_id) runs and wickets per over, with running totals
scorecard(...) / format_scorecard(...) the full card as tables / as printable text
top_batters(balls, n, min_balls, sort_by), top_bowlers(...) leaderboards with minimum-sample filters
phase_table(balls, players, metric) batter × phase grid of any batting metric
innings_totals(balls, matches) one row per innings, merged with match results
season_summary(balls, matches, season), season_table(...) headline numbers for one season / every season

Every function is a few lines of the pandas you learned in this chapter. Here is over_by_over, in full:

def over_by_over(balls: pd.DataFrame, match_id: str) -> pd.DataFrame:
    """Runs and wickets in every over of both innings, with running totals."""
    b = balls[(balls["match_id"] == str(match_id))]
    if "super_over" in b:
        b = b[~b["super_over"]]
    t = (b.groupby(["innings", "over"], as_index=False)
          .agg(team=("batting_team", "first"), bowler=("bowler", "first"),
               runs=("runs_total", "sum"), wickets=("is_wicket", "sum")))
    t["cum_runs"] = t.groupby("innings")["runs"].cumsum()
    t["cum_wickets"] = t.groupby("innings")["wickets"].cumsum()
    return t

code/project_checkpoint.py demonstrates every function. Two highlights from its output. First, season_table reproduces the IPL's season-by-season numbers in one call:

        matches  avg_1st_inns  totals_200_plus  run_rate  rr_powerplay  rr_middle  rr_death  sixes_per_match         top_run_scorer        top_wicket_taker
season                                                                                                                                                     
2022         74         171.1               13      8.54          7.82       8.08     10.45             14.4       JC Buttler (863)          YS Chahal (27)
2023         74         183.0               23      8.99          8.72       8.43     10.49             15.2     Shubman Gill (890)     Mohammed Shami (28)
2024         71         189.6               26      9.56          9.47       8.83     11.21             17.7          V Kohli (741)           HV Patel (24)
2025         74         190.9               32      9.63          9.61       9.03     10.96             17.6  B Sai Sudharsan (759)  M Prasidh Krishna (25)
2026         74         195.7               37      9.88         10.10       9.31     10.79             19.3    V Suryavanshi (776)           K Rabada (29)

Second, because it never hard-codes a competition, the same function summarises the WPL — and flags ties honestly rather than hiding them:

  2022/23: 22 matches, avg 1st inns 156.6, RR 8.08, top bat MM Lanning (345), top bowl HK Matthews (16; tied with 1 other)
  2023/24: 22 matches, avg 1st inns 153.1, RR 7.86, top bat EA Perry (347), top bowl SR Patil (13)
  2024/25: 22 matches, avg 1st inns 162.9, RR 8.37, top bat NR Sciver-Brunt (523), top bowl AC Kerr (18; tied with 1 other)
  2025/26: 22 matches, avg 1st inns 169.1, RR 8.54, top bat S Mandhana (377), top bowl SFM Devine (17; tied with 1 other)

(Ties for the most wickets are broken by fewer runs conceded and then reported as ties — a design choice you should make deliberately rather than let the sort order make for you. Hayley Matthews and Sophie Ecclestone both took 16 in 2022/23.)

How it plugs in. Chapter 4's traditional.py will call top_batters and top_bowlers to show how the traditional leaderboards mislead. Chapter 7's charts.py turns over_by_over into proper Manhattan and worm charts. Chapter 9's win-probability lookup table starts from the same over-by-over states we printed for the 2025 chase. And Chapter 39's dashboard will put format_scorecard behind a match picker. Your task: run python code/project_checkpoint.py, then point season_table at a competition this chapter did not touch — the Big Bash ("bbl"), the PSL ("psl") or the Women's Big Bash ("wbb") — and read the result as a cricket fan. What changed in that league, and when?


🪞 Learning check-in Pause and take stock honestly — nobody else will see this. - Could you, without looking, write the three-line pattern load → filter → groupby for a question of your own, say "most sixes in the 2024 IPL"? If not, which part do you stall on? - Of the silent bugs in §3.9 — season as text, wides in balls faced, super overs, empty filters — which one do you think you are most likely to commit? Write it on a sticky note. - Which felt harder: the Python basics (§3.1–3.3) or the pandas (§3.4–3.8)? If the basics, re-run 01_python_basics.py and change the numbers; if pandas, re-type (don't copy) the groupby examples in §3.6. - What cricket question do you now want to answer that you couldn't a week ago? Keep it — Chapter 4 may answer it, or show you why the obvious answer is wrong.


Chapter Summary

You started with sum([0, 0, 6, 4, 6, 6]) and finished by rebuilding an IPL final's scorecard from raw deliveries and writing reusable code that does the same for any match in the data. The core lesson is a workflow: load → filter → group → merge/reshape → check → plot. The tools:

You want to… pandas idiom Cricket example from this chapter
store one value runs = 43 Kohli's 43 in the 2025 final
store a sequence last_over = [0, 0, 6, 4, 6, 6] Shashank's 22 off Hazlewood
store labelled values {"batter": ..., "runs": ...} one scorecard line
reuse a calculation def batting_strike_rate(runs, balls): ... SR with a zero-balls guard
load a competition load_deliveries("ipl"), load_matches("ipl") 295,732 IPL deliveries
keep some rows balls[balls["phase"] == "death"] 67,173 IPL death deliveries
combine conditions (cond1) & (cond2), \|, ~, .isin([...]) Bumrah, death overs
summarise by group .groupby("batter").agg(runs=("runs_batter", "sum")) 2026 leading run-scorers
add match facts inns.merge(games[[...]], on="match_id", how="left") avg 1st innings 195.7 in 2026
make a grid .pivot_table(index=, columns=, values=, aggfunc=) top-10 × phase strike rates
handle missing .isna(), .notna(), .fillna(), .dropna() winner missing for ties/no-results
use dates .dt.year, .dt.month, .dt.day_name() 2020 IPL played Sep–Nov
running totals .cumsum() (within groupby) the worm chart
plot fig, ax = plt.subplots(); ax.plot(...); fig.savefig(...) Figures 3.1–3.8

Five rules to take into every later chapter:

  1. Balls faced exclude wides; super overs are left out; runs conceded exclude byes and leg-byes. Use the toolkit's summaries and you get these for free.
  2. Filter season with text, or better, with a year from start_date. Check team-name changes before cross-season team analysis.
  3. Every rate needs its sample beside it. Show balls next to strike rates; set and state a minimum.
  4. Check row counts after every filter and merge; treat an empty result as a bug until proven otherwise.
  5. Reconcile — bowlers' runs plus byes and leg-byes should equal the total; a hand-typed list should equal the data.

What's Next

You can now produce any traditional statistic for any player in any competition in the data in a few lines — which is exactly the moment to learn not to trust them. Chapter 4 takes the averages, economy rates and aggregates you just learned to compute and shows, with real players and real numbers, the ways each of them lies: not-outs, pace, phase, conditions, and the selection effect hiding inside Rohit Sharma's average in wins and losses.