Appendix A — Python for Golfers

Every chapter of this book has code, and every number it quotes from that code was printed by a script you can run. This appendix gets you from "I have never typed a line of Python" to "I can read any script in the book, change it, and trust what it prints."

It complements two chapters that teach Python on the job. Chapter 1 (§1.2) flies your first golf ball; Chapter 2 builds the data pipeline and tours pandas on the 2026 Masters. Here we fill the gaps they move past: installation on each operating system, a private environment for the book's packages, the core language, the four scientific libraries, how the book's scripts are built, and what to do when one stops with an error.

Every Python example below is a real script in appendices/_code/appendix_a/, and every output block was pasted from running it. Run them yourself.

If you… Read
have never installed Python A.1 to A.3, then A.4
know some Python but not numpy or pandas A.5 to A.8
know the scientific stack and just want to run the book A.3 (the environment), A.9 (how the scripts work) and A.10 (errors)

A.1 What You Need

You need three things.

  1. Python 3. The book's code was run with Python 3.13.12. Any recent Python 3 should work; if you hit an odd error, matching that version is the first thing to try.
  2. The book's folder, intact. Scripts find the toolkit and data by their position relative to the book's root, so copy the whole folder, not single files.
  3. Five packages: numpy, pandas, scipy, matplotlib and pyarrow (plus pytest for the tests), all listed in requirements.txt (§A.3).

The book's root folder looks like this:

Folder What it holds
part-01-foundations/ … part-08-capstone/ The chapters, each with index.md, exercises, case studies, a code/ folder and an images/ folder
toolkit/golfkit/ golfkit, the book's shared Python toolkit (Appendix B is its reference)
toolkit/tests/ The toolkit's automated tests
project/yardbook/ yardbook, the personal golf analytics package you build one module per chapter (Appendix I)
data/processed/ The seven Parquet tables every chapter reads, plus caches and simulated baselines (Appendix C)
data/reference/ Sourced published facts, each with a source and a confidence tag
data/raw/espn/ The raw JSON download (about 1.1 GB), needed only to rebuild the tables
scripts/ The download and build scripts
appendices/ These appendices, with their scripts in appendices/_code/

The seven Parquet files total about 8 MB, which is why the book's code is fast. Nothing in the chapters needs the network.


A.2 Installing Python

Windows

  1. Download the current Python 3 installer for Windows from python.org.
  2. Run it. On the first screen, tick the box that adds Python to PATH ("Add python.exe to PATH" in recent installers). This one checkbox prevents the commonest Windows problem: a terminal that has never heard of python.
  3. Choose "Install Now".

Windows also installs the Python launcher, py: with several versions installed, py -3.13 runs that one and py --list shows them all. Use PowerShell or Command Prompt as your terminal; they differ only in how they activate a virtual environment (§A.3). If typing python opens the Microsoft Store, that is a shortcut, not Python: install from python.org and open a new terminal.

macOS

A python3 command may already exist on macOS for the system's own tools; don't build on it. Install your own, either with the python.org installer (a .pkg file) or with Homebrew (brew install python). Homebrew's Python refuses pip install outside a virtual environment (an "externally managed environment" error), which is harmless, because you'll use one anyway. Type python3, not python, until you are inside a virtual environment; inside one, both work.

Linux

Most distributions ship Python 3. You usually need two extra pieces: the venv module and pip.

  • Debian and Ubuntu: sudo apt install python3 python3-venv python3-pip
  • Fedora: sudo dnf install python3 python3-pip

Recent distributions mark the system Python as "externally managed", so pip install outside a virtual environment stops with an error. Don't fight it; use a virtual environment.

Check that it worked

In a new terminal:

python --version

(python3 --version on macOS and Linux.) You should see Python 3. followed by a version number. If you see "command not found" or "is not recognized", the installer didn't add Python to your PATH. Reinstall with the PATH box ticked (Windows), or use python3 (macOS, Linux).


A.3 Virtual Environments and requirements.txt

A virtual environment is a private copy of Python with its own installed packages, kept in a folder inside your project. One project wants pandas 2.3, another an older version, and the operating system wants nobody touching its Python. With an environment per project, each gets what it needs, and deleting the folder undoes everything.

Create one

From the book's root folder:

python -m venv .venv

This makes a folder called .venv, built from the Python you just checked (-m venv means "run this Python's venv module").

Activate it

Activation points your terminal's python and pip at the environment's copies.

System and shell Command
Windows, PowerShell .venv\Scripts\Activate.ps1
Windows, Command Prompt .venv\Scripts\activate.bat
macOS or Linux (bash, zsh) source .venv/bin/activate

Your prompt now starts with (.venv). Type deactivate to leave. Every new terminal starts outside the environment, so you activate again each session.

⚠️ Common Pitfall: PowerShell won't run Activate.ps1 PowerShell's default policy can refuse to run local scripts, with a message that running scripts is disabled on this system. Allow scripts for your own user account once with Set-ExecutionPolicy -Scope CurrentUser RemoteSigned, then activate again. If you'd rather not change the policy, use Command Prompt and activate.bat, or skip activation entirely and call the environment's Python directly: .venv\Scripts\python.exe appendices\_code\appendix_a\00_check_setup.py.

Install the book's packages

With the environment active:

python -m pip install -r requirements.txt

-r means "read the list from this file". Here is the file, from the book's root:

# Golf Analytics (DataField.Dev, CC-BY-SA-4.0)
# Python packages used by the golfkit toolkit, the yardbook project and the chapter scripts.
# Install into a virtual environment:  python -m pip install -r requirements.txt
# The book's code was run with Python 3.13 and the versions in the comments.

numpy           # 2.3.5   arrays, random numbers
pandas          # 2.3.3   tables
scipy>=1.9      # 1.17.0  optimisers, statistics, sparse solver; dfs.optimize_lineups needs scipy.optimize.milp (1.9+)
matplotlib      # 3.10.9  charts (golfkit.style)
pyarrow         # 24.0.0  Parquet reader/writer for data/processed/*.parquet

# Tests:  python -m pytest toolkit/tests -q
pytest          # 9.0.2

# Used only by a few Chapter 16 scripts (binomial GLM of birdie odds) and some data-check scripts in scripts/
statsmodels     # 0.14.6

Everything after # is a comment; the comments record the versions the book was run with. Only scipy carries a minimum (>=1.9): the lineup optimiser in Chapter 37 needs a solver that arrived in that release. If a future release ever breaks something, pin it to the commented version (pandas==2.3.3). pyarrow is the engine pandas uses to read the Parquet files in data/processed/; pandas doesn't install it for you (§A.10 shows the error without it).

Use python -m pip, not bare pip. python -m pip always installs into the Python you are running, while a bare pip can belong to another Python on your PATH, which causes most "but I installed it!" errors. To record exactly what you have, python -m pip freeze > my-versions.txt pins every package, dependencies included.

Check the setup

appendices/_code/appendix_a/00_check_setup.py checks everything in one go: it prints your Python and package versions (or "MISSING" with the install command), imports golfkit, loads the data inventory and flies one ball. Run it from the book's root with python appendices/_code/appendix_a/00_check_setup.py. On the machine used for this book it prints:

Python 3.13.12 at python.exe
  numpy       2.3.5
  pandas      2.3.3
  scipy       1.17.0
  matplotlib  3.10.9
  pyarrow     24.0.0
golfkit found in toolkit\golfkit
data: 1,061 events, 7,535,490 hole scores
model check: PGA TOUR driver average carries 282.9 yd

Your version numbers may differ; the last three lines should not. They prove that the toolkit imports, the data loads (the snapshot's exact counts) and the flight model reproduces the carry Chapter 1 checks against TrackMan's published 282 yards.

For a deeper check, run the toolkit's test suite from the book's root:

python -m pytest toolkit/tests -q

It ends with:

128 passed in 23.71s

The time will vary with your machine. The count should not.


A.4 Core Python, One Scorecard at a Time

Here is a hypothetical 18-hole round, typed in by hand, analysed with nothing but plain Python (01_core_python.py):

import sys; from pathlib import Path
BOOK = Path(__file__).resolve().parents[3]          # the book's root folder
sys.path.insert(0, str(BOOK / "toolkit"))           # so that "from golfkit import ..." works
sys.stdout.reconfigure(encoding="utf-8")            # Windows consoles crash on ° and emoji otherwise

# --- values and types -------------------------------------------------------------
course = "Member course"          # str: text
par = 72                          # int: a whole number
course_rating = 70.8              # float: a number with decimals
walked = True                     # bool: True or False
print(type(course).__name__, type(par).__name__, type(course_rating).__name__, type(walked).__name__)

# --- lists: one round's hole scores, in order ---------------------------------------
pars   = [4, 5, 4, 3, 4, 4, 3, 4, 5,  4, 4, 3, 5, 4, 4, 3, 5, 4]
scores = [5, 6, 4, 4, 7, 5, 3, 5, 6,  5, 4, 4, 6, 5, 5, 3, 7, 5]
print("holes:", len(scores), "| total:", sum(scores), "| front nine:", sum(scores[:9]), "| back nine:", sum(scores[9:]))
print("hole 5 (index 4):", scores[4], "on a par", pars[4])

# --- loops and conditions: name every score -----------------------------------------
NAMES = {-2: "eagle", -1: "birdie", 0: "par", 1: "bogey", 2: "double"}
counts = {}
for hole, (p, s) in enumerate(zip(pars, scores), start=1):
    name = NAMES.get(s - p, "triple+" if s - p > 2 else "albatross")
    counts[name] = counts.get(name, 0) + 1
    if s - p >= 2:
        print(f"  hole {hole:>2}: {s} on a par {p} ({name})")
print("score mix:", counts)

# --- dicts: a club-distance chart (yards, carry) ------------------------------------
carry = {"7i": 145, "8i": 135, "9i": 124, "PW": 112}
target = 131
best = min(carry, key=lambda club: abs(carry[club] - target))
print(f"{target} yd to the pin: closest club is {best} ({carry[best]} yd)")

# --- functions: a Score Differential, written by hand -------------------------------
def score_differential(ags: int, rating: float, slope: int, pcc: float = 0.0) -> float:
    """WHS Score Differential = (113 / Slope) x (AGS - Course Rating - PCC), to one decimal."""
    return round(113 / slope * (ags - rating - pcc), 1)

print("differential:", score_differential(sum(scores), course_rating, 125))

# --- comprehensions and f-strings ---------------------------------------------------
to_par = [s - p for s, p in zip(scores, pars)]
pars_made = sum(1 for x in to_par if x == 0)
print(f"to par by hole: {to_par}")
print(f"{pars_made} pars, {sum(to_par):+d} for the round, {sum(scores) / 18:.2f} strokes per hole")

# --- a rounding trap: Python's round() rounds halves to EVEN; the WHS rounds .5 UP ---
from golfkit import whs
for x in (0.25, 16.45, 2.5):
    print(f"round({x}, 1) = {round(x, 1)}   whs.round_tenth({x}) = {whs.round_tenth(x)}")

Output:

str int float bool
holes: 18 | total: 89 | front nine: 45 | back nine: 44
hole 5 (index 4): 7 on a par 4
  hole  5: 7 on a par 4 (triple+)
  hole 17: 7 on a par 5 (double)
score mix: {'bogey': 12, 'par': 4, 'triple+': 1, 'double': 1}
131 yd to the pin: closest club is 8i (135 yd)
differential: 16.5
to par by hole: [1, 1, 0, 1, 3, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 2, 1]
4 pars, +17 for the round, 4.94 strokes per hole
round(0.25, 1) = 0.2   whs.round_tenth(0.25) = 0.3
round(16.45, 1) = 16.4   whs.round_tenth(16.45) = 16.5
round(2.5, 1) = 2.5   whs.round_tenth(2.5) = 2.5

The rating and slope (CR 70.8 / Slope 125) are the book's simulated member course's, 🧪 assumed values for a typical member tee (Appendix B, golfkit.holes). The ideas, in order:

  • Values and types. par = 72 attaches a name to a value. The four everyday types are str (text), int, float and bool; type(x) tells you which you have. 72 and "72" look alike on a scorecard, but "72" + 1 is an error.
  • Lists and indexing. A list is ordered, so it suits hole scores. Python counts from zero: scores[4] is the fifth hole, which trips up every golfer once. Slices take ranges: scores[:9] is the front nine (up to, not including, index 9) and scores[9:] the back nine.
  • Loops. A for loop runs its indented block once per item. zip(pars, scores) walks two lists side by side; enumerate(..., start=1) adds a hole counter that starts at 1. Indentation is the syntax: use four spaces per level and never mix tabs and spaces.
  • Dictionaries. A dict maps keys to values, like a club chart (carry["8i"] is 135). .get(key, default) returns the default instead of crashing on a missing key, and counts.get(name, 0) + 1 is the counting idiom. min(carry, key=...) returns the key with the smallest value of the key function, here the error to 131 yards.
  • Functions. def defines reusable code with parameters and a return. Copy the habits in score_differential: type hints (ags: int, -> float), defaults (pcc: float = 0.0) and a docstring, which help(score_differential) prints. Every golfkit function is written this way, which is why Appendix B can list their signatures and units.
  • Comprehensions and f-strings. [s - p for s, p in zip(scores, pars)] builds a list in one line. An f-string drops values into text, with a format after the colon:
Format Meaning Example output
{x:.2f} two decimal places 4.94
{x:+d} integer with a sign +17
{x:>2} right-aligned in 2 characters 5
{x:,} thousands separators 7,535,490
{x:.1%} as a percentage 10.1%

The rounding trap

The World Handicap System rounds Score Differentials to the nearest tenth with .5 rounded up (Chapter 29). Python's round() rounds exact halves to the even digit (0.25 becomes 0.2), and it works on the stored binary value, which for 16.45 is a hair below 16.45 (so 16.4). golfkit.whs.round_tenth implements the handicap rule. Our hand-written function used round(); it was right for this round and would be wrong for others. When a rule says how to round, implement the rule and test the edge cases.

🔄 Check Your Understanding 1. What does scores[17] return, and which hole is it? 2. What name does the loop give a 2 on a par 4, and why doesn't it need the .get default? 3. Why might round(113 / 125 * (93 - 70.8), 1) disagree with the handicap rule for some scores?

Answers

  1. 5, the score on the 18th hole (index 17, because counting starts at 0).
  2. "eagle". A 2 on a par 4 is s - p = -2, which is a key in NAMES, so .get finds it. The default is used only for keys that aren't there (+3 or worse, or −3 or better).
  3. round() rounds exact halves to even and works on the stored binary value, while the WHS rounds .5 up. Use whs.round_tenth or whs.score_differential.

A.5 numpy: Whole Rounds at Once

numpy stores numbers in arrays and does arithmetic on whole arrays at once, in fast compiled code. For golf data that means no loops over holes, shots or rounds. 02_numpy_basics.py:

import sys
sys.stdout.reconfigure(encoding="utf-8")
import numpy as np

pars   = np.array([4, 5, 4, 3, 4, 4, 3, 4, 5, 4, 4, 3, 5, 4, 4, 3, 5, 4])
scores = np.array([5, 6, 4, 4, 7, 5, 3, 5, 6, 5, 4, 4, 6, 5, 5, 3, 7, 5])
to_par = scores - pars                       # element by element, no loop
print("to par:", to_par, "| total", to_par.sum())
print("par-3 average:", scores[pars == 3].mean(), "| par-5 average:", scores[pars == 5].mean())
print("holes over bogey:", np.flatnonzero(to_par >= 2) + 1)

# 🧪 1,000 seeded 7-iron shots at a 150-yd pin: lateral SD 12 yd, distance SD 8 yd, no bias
rng = np.random.default_rng(2026)
lat  = rng.normal(0.0, 12.0, size=1000)      # + = right of the target line
long = rng.normal(0.0, 8.0, size=1000)       # + = long of the pin
on_green = (np.abs(lat) <= 13) & (np.abs(long) <= 15)   # a 26-yd-wide, 30-yd-deep green
print(f"lateral SD {lat.std(ddof=1):.2f} yd, distance SD {long.std(ddof=1):.2f} yd")
print(f"share on the green: {on_green.mean():.3f}; median miss distance {np.median(np.hypot(lat, long)):.1f} yd")
print(f"same seed, same numbers: {np.allclose(np.random.default_rng(2026).normal(0, 12, 1000), lat)}")

Output:

to par: [1 1 0 1 3 1 0 1 1 1 0 1 1 1 1 0 2 1] | total 17
par-3 average: 3.5 | par-5 average: 6.25
holes over bogey: [ 5 17]
lateral SD 12.37 yd, distance SD 7.82 yd
share on the green: 0.669; median miss distance 11.8 yd
same seed, same numbers: True

🧪 Assumption: the 7-iron pattern (12 yd lateral SD, 8 yd distance SD, centred on the pin) and the rectangular 26 × 30-yd green are teaching values, not a measured golfer or a real green. They are in the range Chapter 19 works with, and the point here is the code, not the numbers.

What to notice:

  • Vectorised arithmetic. scores - pars subtracts hole by hole. The same line works for 18 holes or 7.5 million.
  • Boolean masks. pars == 3 is an array of True/False; scores[pars == 3] keeps only the par 3s. Combine conditions with & and |, each in parentheses (Python's and/or don't work on arrays). The mean of a mask is a share, so on_green.mean() is the fraction of greens hit. np.flatnonzero returns the positions where a condition holds (add 1 for hole numbers).
  • ddof=1 gives the usual sample SD (divide by n − 1). numpy's default divides by n, which matters for a 20-shot launch-monitor session.
  • Seeds. np.random.default_rng(2026) fixes the random numbers, so anyone can reproduce a simulated result exactly. Every random script in the book states its seed.

The sample SDs (12.37 and 7.82) are not exactly the 12 and 8 we asked for. That is sampling variation, and it is why the book always says how many shots or rounds lie behind a number (dispersion.shots_needed in Appendix B gives 51 shots for a ±10% standard error on an SD).


A.6 pandas: Tables of Tour Data

pandas gives you the DataFrame: a table with named columns, like a spreadsheet you program. Chapter 2 tours pandas on the 2026 Masters. Here is a different event, THE PLAYERS Championship 2026, and a few operations Chapter 2 uses without stopping to explain them (03_pandas_basics.py):

import sys; from pathlib import Path
BOOK = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(BOOK / "toolkit")); sys.path.insert(0, str(BOOK / "project"))
sys.stdout.reconfigure(encoding="utf-8")
import pandas as pd
from golfkit import data

# 1. A Parquet file is just a table on disk; pandas reads it in one line.
raw = pd.read_parquet(BOOK / "data" / "processed" / "events.parquet")
print("events.parquet:", raw.shape, "| first columns:", list(raw.columns[:6]))

# 2. The golfkit loaders add the book's flags; filter rows with a boolean condition.
ev = data.event_lookup("PLAYERS", year=2026)
print(ev[["event_id", "name", "end_date", "major"]].to_string(index=False))
eid = ev["event_id"].iloc[0]

# 3. Rounds: one row per player-round. groupby + agg summarises each round of the week.
rd = data.rounds(event_ids=[eid])
print(rd.groupby("round")["score"].agg(["count", "mean", "min", "max"]).round(2).to_string())

# 4. Holes: one row per hole score. The famous 17th, by score type.
ho = data.holes(event_ids=[eid])
h17 = ho[ho["hole"] == 17]
print("hole 17 par:", h17["par"].unique(), "| scores:", h17["strokes"].value_counts().sort_index().to_dict())
print(f"hole 17 average {h17['strokes'].mean():.3f} over {len(h17)} hole scores")

# 5. merge: attach names (validate= makes pandas check the join is many-to-one).
pe = data.player_events(event_ids=[eid]).merge(data.players(), on="player_id", how="left", validate="many_to_one")
top = pe.sort_values("position_fixed").head(3)
print(top[["name", "position_fixed", "total_fixed", "status_fixed"]].to_string(index=False))

# 6. pivot: the winner's scorecard, long -> wide (rounds as rows, holes as columns).
win_id = pe.loc[pe["won_fixed"], "player_id"].iloc[0]
card = ho[ho["player_id"] == win_id].pivot(index="round", columns="hole", values="strokes")
card["total"] = card.sum(axis=1)
print(card.to_string())

Output:

events.parquet: (1061, 24) | first columns: ['event_id', 'name', 'start_date', 'end_date', 'season', 'major']
 event_id                     name   end_date major
401811937 THE PLAYERS Championship 2026-03-15  None
       count   mean   min   max
round                          
1        122  73.13  67.0  84.0
2        122  72.39  63.0  83.0
3         73  71.47  65.0  81.0
4         73  72.67  67.0  80.0
hole 17 par: [3] | scores: {2: 52, 3: 279, 4: 37, 5: 16, 6: 4, 7: 2}
hole 17 average 3.095 over 390 hole scores
             name  position_fixed  total_fixed status_fixed
    Cameron Young             1.0        275.0     finished
 Matt Fitzpatrick             2.0        276.0     finished
Xander Schauffele             3.0        277.0     finished
hole   1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  total
round                                                                      
1      4  4  3  3  4  4  4  3  4   4   5   4   3   4   5   4   3   3     68
2      4  4  3  4  4  4  4  2  6   4   4   4   3   3   3   5   2   4     67
3      4  5  4  4  4  3  4  3  5   4   4   4   2   5   4   5   2   6     72
4      3  5  3  4  4  5  3  3  5   3   5   4   2   4   4   5   2   4     68

All of this is REAL: ESPN's hole-by-hole scores, read through golfkit.

  1. Reading Parquet. pd.read_parquet(path) loads a table; .shape is (rows, columns) and .columns lists the names, the first thing to print when you get a KeyError (§A.10).
  2. Loaders, not raw tables. The book reads data through golfkit.data, because its loaders add the flags the analysis depends on: calendar year, stroke_play_ok, multicourse, par_ok and the corrected finish columns (Appendix C lists them). event_lookup matches part of a name within one calendar year.
  3. groupby. Split the rows by round, take score, summarise each group: the most useful idiom in golf analysis. The counts show the cut, 122 complete rounds in rounds 1 and 2 and 73 in rounds 3 and 4 (data.rounds keeps complete 18-hole rounds by default).
  4. Filtering and counting. ho[ho["hole"] == 17] is the numpy mask applied to a table, and value_counts() counts each value. The island-green 17th produced 52 birdies, 279 pars and 22 double bogeys or worse in 390 hole scores. Chapter 31 checks ESPN's counts on this hole against the PGA TOUR's ShotLink water-ball figures.
  5. merge. Joins two tables on a shared key (player_id). how="left" keeps every left row; validate="many_to_one" makes pandas raise an error if a player appears twice in the names table, which stops silent duplicate rows. And note the columns: always use the *_fixed outcome columns for finishes, cuts and wins; the build's first-pass status labels any player with a missing hole a withdrawal (Appendix C, §C.3).
  6. pivot. The holes table is long (one row per hole score); pivot reshapes it wide, into a scorecard. Store long, pivot for display.

⚠️ Common Pitfall: chained assignment Code like ho[ho["hole"] == 17]["strokes"] = 3 looks like it changes the 17th-hole scores, but it may change a temporary copy and leave the table untouched. pandas warns about this. Use .loc with both the row condition and the column in one step: ho.loc[ho["hole"] == 17, "strokes"] = 3. Better still, don't overwrite real data; make a new column.


A.7 matplotlib with golfkit.style

matplotlib draws the book's charts, and golfkit.style makes them look like one book. 04_matplotlib_style.py draws hole difficulty at THE PLAYERS 2026:

import sys; from pathlib import Path
BOOK = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(BOOK / "toolkit")); sys.path.insert(0, str(BOOK / "project"))
from golfkit import style; style.use()                 # house fonts, colours, grid
sys.stdout.reconfigure(encoding="utf-8")
IMG = BOOK / "appendices" / "images"; IMG.mkdir(exist_ok=True)
import matplotlib.pyplot as plt
from golfkit import data

eid = data.event_lookup("PLAYERS", year=2026)["event_id"].iloc[0]
hs = data.hole_scoring(event_id=eid).sort_values("hole")       # one row per hole
fig, ax = plt.subplots(figsize=(8, 3.6))
colors = style.sg_colors(-hs["to_par"])                        # harder than par -> orange (a loss)
ax.bar(hs["hole"], hs["to_par"], color=colors)
ax.axhline(0, color=style.TEXT_2, lw=0.8)
ax.set_xticks(hs["hole"])
ax.set_xlabel("Hole"); ax.set_ylabel("Strokes vs par (field average)")
ax.set_title("THE PLAYERS 2026: field average vs par, by hole")
style.save(fig, IMG / "appa-fig-players-2026-holes.png",
           note="Data: ESPN PGA TOUR hole-by-hole scores, 2004–2026 (golfkit)")
h = hs.set_index("hole")["to_par"]
print(f"hardest hole {h.idxmax()} ({h.max():+.3f}); easiest hole {h.idxmin()} ({h.min():+.3f})")
print(f"hole 17: {h[17]:+.3f}; par 5s: {hs.loc[hs.par == 5, 'to_par'].round(3).tolist()}")

Output:

hardest hole 18 (+0.338); easiest hole 16 (-0.403)
hole 17: +0.095; par 5s: [-0.323, -0.208, -0.231, -0.403]

Figure A.1 — THE PLAYERS 2026: field average vs par, by hole

📊 Figure (described): A bar chart with one bar per hole, 1 to 18, showing the field's average score relative to par. Thirteen bars rise above zero in orange (holes that played over par), the tallest at the 18th (+0.34) and the 14th (+0.28). Five bars drop below zero in blue: the four par 5s (holes 2, 9, 11 and 16), the deepest at the 16th (−0.40), and a sliver at the 365-yard par-4 12th (−0.03). A grey line marks par. A small note in the bottom-left corner gives the data source.

Only the four par 5s and the short 12th played under par, and the 18th, not the famous 17th, was the hardest hole of the week (+0.338 against +0.095).

The pattern of every chart in the book:

  1. style.use() once, at the top. It sets the fonts, the white background, the light grid and the fixed colour order.
  2. fig, ax = plt.subplots(...) makes a figure (the canvas) and an axes (the plot inside it). Everything you draw is a method on ax: ax.bar, ax.plot, ax.scatter, ax.set_xlabel.
  3. Colour by meaning, not decoration. - style.SERIES is the categorical palette, used in its fixed order (style.SERIES[0] for the first series, [1] for the second), never cycled at random. - style.sg_colors(values) returns blue for gains and orange for losses, the book's strokes-gained pair. We passed -to_par because, for a golfer, a hole that plays over par is a loss.
  4. style.save(fig, path, note=...) writes the PNG and adds the source note. The note is not optional in this book. Real data gets "Data: ESPN PGA TOUR hole-by-hole scores, 2004–2026 (golfkit)". Simulated data gets "SIMULATED — golfkit.shotsim, seed N". Anything hypothetical says so.

⚠️ Common Pitfall: an empty window after style.save style.save closes the figure after writing it, so a plt.show() placed after it has nothing to show. To look at a chart interactively, call plt.show() instead of saving, or open the PNG. style.save also expects the folder to exist, which is why every script makes its images/ folder first (IMG.mkdir(exist_ok=True)).


A.8 scipy: Solvers and Statistics

scipy holds the numerical machinery: root finders and optimisers, probability distributions, statistical tests, and the sparse solver behind the book's strokes-gained model. 05_scipy_basics.py shows three tools in golf terms:

import sys; from pathlib import Path
BOOK = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(BOOK / "toolkit")); sys.path.insert(0, str(BOOK / "project"))
sys.stdout.reconfigure(encoding="utf-8")
import numpy as np
from scipy import optimize, stats
from golfkit import flight, data, shotsim
from yardbook import cast

# 1. Root finding: the ball speed that carries a bunker 230 yd away (launch 12 deg, spin 2,600 rpm).
def short_of_carry(ball_mph):
    return flight.launch(ball_mph, 12.0, 2600, record_path=False).carry - 230.0
v = optimize.brentq(short_of_carry, 120, 180, xtol=0.01)   # brackets: too slow, plenty fast
print(f"ball speed needed to carry 230 yd: {v:.1f} mph (check: {flight.launch(v, 12.0, 2600).carry:.1f} yd)")

# 2. Confidence interval: Rosa's representative 20-round sample (SIMULATED, see cast.py).
shots = cast.cast_rounds("Rosa")
score = shotsim.round_summary(shots)["score"].to_numpy(float)
m, s, n = score.mean(), score.std(ddof=1), len(score)
lo, hi = stats.t.interval(0.95, df=n - 1, loc=m, scale=s / np.sqrt(n))
print(f"Rosa: {n} rounds, mean {m:.2f}, SD {s:.2f}, 95% CI for her mean {lo:.2f} to {hi:.2f}")
print(f"normal-curve chance of breaking 90 in one round: {stats.norm.cdf(89.5, m, s):.3f}")

# 3. Regression: do longer par 4s play harder? REAL 2026 event-holes.
hs = data.hole_scoring(years=[2026])
p4 = hs[(hs["par"] == 4) & hs["yards"].notna()]
fit = stats.linregress(p4["yards"], p4["to_par"])
print(f"{len(p4)} par-4 event-holes: {100 * fit.slope:+.3f} strokes per 100 yd, r = {fit.rvalue:.3f}")

Output:

ball speed needed to carry 230 yd: 144.6 mph (check: 230.0 yd)
Rosa: 20 rounds, mean 93.40, SD 5.81, 95% CI for her mean 90.68 to 96.12
normal-curve chance of breaking 90 in one round: 0.251
529 par-4 event-holes: +0.248 strokes per 100 yd, r = 0.725

1. A root finder. optimize.brentq(f, a, b) finds the input where f crosses zero, given two brackets where f has opposite signs: at 120 mph the ball comes up short of 230 yards and at 180 mph it flies past. We wrapped the flight model in a small function that returns "carry minus 230", and scipy found the ball speed that makes it zero: 144.6 mph (golfkit model, standard sea-level air, with the launch and spin held fixed). This pattern (wrap a model in a function, then ask scipy for the input that hits a target) solves a surprising number of golf questions: the club speed for a carry, the aim for a putt, the break-even probability for a risky play.

2. A confidence interval. Rosa Delgado is one of the book's six fictional golfers, and her rounds are SIMULATED (yardbook.cast, her representative 20-round sample; see cast.py). Her 20 scores average 93.40 with an SD of 5.81. stats.t.interval turns that into a 95% confidence interval for her true average: 90.68 to 96.12, more than five strokes wide after 20 rounds. That width is theme 5 of the book in one line, and Chapter 14 builds the whole argument.

stats.norm.cdf(89.5, m, s) gives the area under a normal curve below 89.5, read as the chance of a score of 89 or better: 0.251. Treat it as rough. It is a 🧪 normal approximation, and golf scores are not quite normal: blow-up holes give them a longer tail on the high side.

3. A regression. stats.linregress(x, y) fits a straight line. Across 529 par-4 event-holes on the 2026 PGA TOUR (REAL, ESPN yardages and scoring averages), every extra 100 yards of length came with +0.248 strokes of scoring average, and the correlation was 0.725. Length explains a lot of par-4 difficulty, but not all of it. Chapter 16 and Chapter 39 model hole difficulty properly.


A.9 Reading the Book's Scripts

Every script in the book follows one template, so once you can read one, you can read them all.

The docstring

The script opens with a docstring in four parts: Purpose (what it does), Data (what it reads), Output (what it prints and which image files it writes) and often Run (the command). Read the Data line before you trust a single number. It tells you which of the book's three kinds of number you're looking at: REAL (ESPN scores), SIMULATED (golfkit.shotsim, with a seed), or a model or published value (data/reference/, with its source).

The standard header

Next comes the same six-line header in every script:

import sys; from pathlib import Path
BOOK = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(BOOK / "toolkit")); sys.path.insert(0, str(BOOK / "project"))
from golfkit import style; style.use()
sys.stdout.reconfigure(encoding="utf-8")   # Windows consoles crash on ° and emoji otherwise
IMG = Path(__file__).resolve().parents[1] / "images"; IMG.mkdir(exist_ok=True)
Line What it does
Path(__file__).resolve() The full path of this script file
.parents[3] Three folders up from the script's own folder: from part-…/chapter-…/code/script.py that is the book's root. (The appendix scripts sit at the same depth, in appendices/_code/appendix_a/)
sys.path.insert(0, …) Puts toolkit/ and project/ at the front of the list of places Python searches for modules, so from golfkit import … and from yardbook import … work without installing anything
style.use() The house chart style (§A.7)
sys.stdout.reconfigure(encoding="utf-8") Lets the console print °, −, 🧪 and the other symbols the book uses (§A.10)
IMG = … The chapter's images/ folder, created if it doesn't exist

Because every path is built from the script's own location, it doesn't matter which folder your terminal is in. python code/01_first_trajectory.py from the chapter folder (Chapter 1's habit) and python part-01-foundations/chapter-01-ball-flight-physics/code/01_first_trajectory.py from the book's root both work. What breaks the scripts is moving one: copy a script to your desktop and parents[3] points at the wrong folder.

The body

After the header, a script usually does four things: it loads data through golfkit (or simulates it with a stated seed); it computes; it prints every number the chapter quotes; and it saves figures with a source note. Some conventions to recognise:

  • Seeds are explicit. rng = np.random.default_rng(2026), simulate_rounds(..., seed=1), cast_rounds("Rosa") (which uses Rosa's documented default seed). Change the seed and you see a different, equally valid sample, which is often the most instructive experiment you can run.
  • SIMULATED is printed, not implied. Simulated results carry the word in the printout and on the figure.
  • Excerpts in the chapters are short. A chapter shows up to 25 commented lines and names the full script. The script is the authority.
  • Heavy work is cached. The strokes-gained table, the tournament walk-forward and the simulated baselines are saved in data/processed/cache/ and data/processed/baselines/ the first time they're built, so later runs take a fraction of a second. The cache keys include the source files' timestamps, so a rebuilt dataset invalidates them automatically. Deleting the cache folder forces a rebuild.
  • Each script runs in under three minutes. If one runs much longer, something is wrong (a missing cache is the usual cause), and §A.10 has the checks.

Exploring an unfamiliar function

You don't need to memorise golfkit. Python can tell you about any function:

  • help(flight.launch) prints its docstring.
  • import inspect; inspect.signature(flight.launch) prints its parameters and defaults.
  • dir(flight) lists everything in a module.

Appendix B was written by doing exactly that for every module, and then checking each signature against the code.


A.10 Common Errors and How to Fix Them

Python errors arrive as a traceback: a stack of the calls that led to the problem, ending with the error itself. Read tracebacks from the bottom up. The last line names the error and its message. The lines above show where it happened, and the lowest line that points into your file is usually the one to fix.

Each error below was produced by a real script in appendices/_code/appendix_a/errors/, and the output is pasted from running it.

UnicodeEncodeError (Windows)

A script without the reconfigure line, printing a label the way the book does:

print("🧪 assumed lateral SD 12 yd; SG −1.55")

On a Windows console using the legacy code page, the last line of the traceback is:

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

The console's encoding (cp1252 here) has no 🧪. It has no proper minus sign (−) either, which the book uses for every negative strokes-gained value. There are three fixes; use any one:

  1. In the script: sys.stdout.reconfigure(encoding="utf-8"), which is why every script in the book has that line.
  2. For one run: python -X utf8 script.py.
  3. For good: set the environment variable PYTHONUTF8=1 (in PowerShell, $env:PYTHONUTF8 = "1" for the current session; set it in Windows' environment-variable settings to make it permanent).

Run with the second fix, the same script prints:

🧪 assumed lateral SD 12 yd; SG −1.55

A related symptom: text that prints but shows � where a dash or symbol should be. That is the same mismatch with a gentler error handler. The same fixes apply.

ModuleNotFoundError: No module named 'golfkit'

from golfkit import flight
ModuleNotFoundError: No module named 'golfkit'

golfkit isn't installed with pip. Python finds it because of the sys.path.insert lines in the standard header. You'll see this error if you leave the header out, if you moved the script out of the book's folder structure, or if you're typing into an interactive Python session started somewhere else. In an interactive session, start Python in the book's root folder and add the path yourself:

import sys; from pathlib import Path; sys.path.insert(0, str(Path.cwd() / "toolkit"))

Path.cwd() is the folder the session started in. If you started elsewhere, give the full path to the book's toolkit folder instead, as a raw string (r"...") on Windows so that backslashes aren't read as escape characters.

ModuleNotFoundError: No module named 'numpy' (or pandas, scipy …)

The package isn't installed in the Python that is running the script. Usually it is installed, but in a different Python. Check three things:

  1. Is your virtual environment active? (Is (.venv) in your prompt?)
  2. Which Python is running? python -c "import sys; print(sys.executable)" prints its path.
  3. Install with that same Python: python -m pip install -r requirements.txt.

Editors such as VS Code choose their own interpreter. If a script works in the terminal but not from the editor's Run button, point the editor at .venv.

ImportError: Unable to find a usable engine (Parquet)

errors/e6_no_pyarrow.py hides pyarrow from Python, then reads a table:

sys.modules["pyarrow"] = None            # simulate a missing package (for this demonstration only)
import pandas as pd
pd.read_parquet(Path(__file__).resolve().parents[4] / "data" / "processed" / "events.parquet")

The traceback ends with:

ImportError: Unable to find a usable engine; tried using: 'pyarrow', 'fastparquet'.
A suitable version of pyarrow or fastparquet is required for parquet support.
Trying to import the above resulted in these errors:
 - Missing optional dependency 'pyarrow'. pyarrow is required for parquet support. Use pip or conda to install pyarrow.
 - Missing optional dependency 'fastparquet'. fastparquet is required for parquet support. Use pip or conda to install fastparquet.

Fix: python -m pip install pyarrow (it is in requirements.txt).

FileNotFoundError from a relative path

import pandas as pd
rounds = pd.read_parquet("data/processed/rounds.parquet")

Run from inside the appendices/_code/appendix_a/ folder, this ends with:

FileNotFoundError: [Errno 2] No such file or directory: 'data/processed/rounds.parquet'

Run from the book's root, the identical script works. A relative path like "data/processed/…" is resolved from the terminal's current folder, not from the script's folder. That is why the book's scripts build every path from BOOK (BOOK / "data" / "processed" / "rounds.parquet"), or let golfkit find the files. Do the same in your own scripts.

If the file is missing even from the right place, your copy of the book lacks data/processed/. Get the complete folder, or rebuild the tables from the raw download (Appendix C, §C.7).

KeyError on a column name

rd = data.rounds(years=[2026])
print(rd["Score"].mean())
KeyError: 'Score'

Column names are case-sensitive, and this one is score. print(rd.columns.tolist()) lists the real names, and Appendix C lists every table's columns.

ValueError from a toolkit function

Some golfkit functions refuse impossible requests instead of returning a wrong answer. Ask for the plays-like yardage of a 150-yard 7-iron into a 20 mph headwind:

from golfkit import weather
print(weather.plays_like(150, "7-iron", wind_mph=20, wind_from_deg=0))
ValueError: out of reach: with spin scaled to ball speed this club's flight balloons before it gets there — use a longer club's profile

The message says what to do: pass a longer club's launch profile. When a toolkit function raises an error, read its message before anything else. golfkit's messages are written to be acted on. Appendix B lists the cases where a function doesn't raise when it should, which are the dangerous ones.

Other problems you may meet

Symptom Likely cause Fix
python opens the Microsoft Store (Windows) A Store shortcut, not Python Install from python.org with "Add to PATH"; open a new terminal
"externally managed environment" from pip (macOS Homebrew, Linux) Installing into the system Python Create and activate a virtual environment (§A.3)
PowerShell won't run Activate.ps1 Script execution policy Set-ExecutionPolicy -Scope CurrentUser RemoteSigned, or use Command Prompt (§A.3)
A script takes far longer than usual on its first run A cache is being built (strokes-gained table, baselines, walk-forward) Let it finish once; later runs read the cache
Numbers differ slightly from the chapter A changed seed, a different simulation size n, or a rebuilt dataset Check the seed and n against the script's docstring. For REAL numbers, check your data snapshot's counts with data.inventory()
A chart window is blank plt.show() after style.save, which closes the figure Show or save, not both (§A.7)
SettingWithCopyWarning Chained assignment in pandas Use .loc[rows, column] = value (§A.6)
IndentationError or SyntaxError before anything runs A missing colon after for/if/def, an unclosed bracket on the line above the one reported, mixed tabs and spaces, or curly quotes pasted from a web page Fix the line Python points at, or the one just above it

A.11 Where to Go Next

  • Run Chapter 1's first script, then change the launch numbers and watch the carry move.
  • Work through Chapter 2 §2.6 for a longer pandas session on the 2026 Masters.
  • Keep Appendix B (the golfkit reference) open while you read Parts II to VII.
  • Read Appendix C before you build anything on the tour data: it lists every table, column and data-quality fix.
  • Appendix E covers the statistics behind the confidence intervals and regressions used here.
  • Appendix I explains the yardbook project, the package you build alongside the chapters.

Python is a tool, like a rangefinder. It doesn't swing the club for you, but it tells you, honestly and to the yard, what you're working with.