Skip to content

Printable cheat sheet

This page joins all 57 master cheat sheet pages into one, in reading order. Use your browser’s Print command (Ctrl+P or Cmd+P) to print it or save it as a PDF. The print styles hide the site navigation, use a compact code font and open every collapsed block.

For everyday use, the separate pages are faster to search: start at the cheat sheet overview.

The core language on one page: literals and types, operators, truthiness, conversion, numbers (int, float, Decimal, Fraction), None, and every control-flow form from if to match and comprehensions. Every runnable block is checked against its output on Python 3.13.

I want to… Use… Example
check a type isinstance(x, T) (a tuple of types also works) isinstance(3, (int, float)) → True
see the exact type type(x) type(1e3) → float
write a big number readably underscores in the literal 1_000_000
write binary, octal or hex 0b, 0o, 0x 0xFF → 255
parse text in any base int(text, base) int("ff", 16) → 255
show a number in binary or hex bin(), hex(), f"{n:08b}" f"{5:08b}" → 00000101
divide and drop the remainder // (floors toward minus infinity) -7 // 2 → -4
get quotient and remainder divmod(a, b) divmod(555, 60) → (9, 15)
round to n decimals round(x, n) (halves go to even) round(2.5) → 2
round halves up (money) Decimal.quantize(..., ROUND_HALF_UP) see Numbers
floor, ceil, truncate math.floor, math.ceil, math.trunc math.ceil(2.1) → 3
compare floats math.isclose(a, b) math.isclose(0.1 + 0.2, 0.3) → True
exact decimal arithmetic Decimal("0.10") (from a string) Decimal("0.1") + Decimal("0.2")
exact fractions Fraction(1, 3) Fraction(1, 3) * 3 → 1
infinity and NaN math.inf, math.nan, math.isnan(x) math.isnan(float("nan"))
test for a missing value x is None if reading is None:
give a default for None only x if x is not None else default 0 stays 0
give a default for any falsy value x or default "" or "n/a" → 'n/a'
test a range chained comparison 0 <= x < 10
test membership in "a" in "cat", k in d
assign inside an expression walrus := while (line := f.readline()):
choose between two values conditional expression "odd" if n % 2 else "even"
branch on the shape of data match / case see match
loop with an index enumerate(seq, start=1) for i, x in enumerate(xs, 1):
loop over two sequences together zip(a, b, strict=True) fails if lengths differ
loop backward reversed(seq) or range(n - 1, -1, -1) for x in reversed(xs):
run code when a loop did not break for ... else search loops
skip to the next iteration continue
build a list from a loop list comprehension [x * 2 for x in xs if x > 0]
do nothing in a block pass or ... def todo(): ...
swap two variables tuple assignment a, b = b, a
unpack “first and the rest” star target first, *rest = items
run code only when the file is run as a script if __name__ == "__main__": not on import
Type Literal forms Notes
int 42, -7, 1_000_000, 0b1010, 0o17, 0xFF arbitrary precision; no long
float 3.14, .5, 2., 1e-3, 6.02e23, 1_000.5 IEEE 754 double, about 15–17 significant digits
complex 2j, 1 + 2j .real, .imag, abs(z)
bool True, False a subclass of int: True + True == 2
str 'a', "a", """multi-line""", r"C:\path", f"{x}" immutable Unicode text
bytes b"raw", rb"\d" immutable bytes (ASCII in the literal)
NoneType None the only value of its type
list [], [1, 2], [1, 2,] trailing comma allowed
tuple (), (1,), 1, 2 the comma makes the tuple, not the parentheses
dict {}, {"a": 1}, {**d, "b": 2} {} is an empty dict
set {1, 2}, set() there is no empty-set literal
range range(5), range(1, 10, 2) lazy, immutable sequence
Ellipsis ... placeholder body, NumPy slicing
Type Mutable Hashable (dict key) Ordered Duplicates Typical use
int, float, bool, complex no yes — — numbers, flags
str, bytes no yes yes yes text, raw data
tuple no yes, if all items are yes yes records, dict keys
frozenset no yes no no set as a dict key
list yes no yes yes ordered collections
dict yes no insertion order unique keys lookups by key
set yes no no no membership, dedupe
bytearray yes no yes yes editable bytes
NoneType no yes — — “no value”
values = [7, 7.0, 7j, True, None, (), (1,), {}, set(), b"", range(3)]
print([type(v).__name__ for v in values])
print(isinstance(True, int), isinstance(3, (int, float)), issubclass(bool, int))
Output
['int', 'float', 'complex', 'bool', 'NoneType', 'tuple', 'tuple', 'dict', 'set', 'bytes', 'range']
True True True
Form Example Meaning
simple x = 1 bind the name x to the object 1
multiple a, b = 1, 2 tuple unpacking
swap a, b = b, a right side is built first
chained a = b = [] both names point to the same list
augmented x += 1, s *= 2, n //= 3 in place for mutable objects (list += mutates)
star unpacking first, *middle, last = seq middle is always a list
nested unpacking (a, b), c = (1, 2), 3 shapes must match
walrus if (n := len(xs)) > 3: assign and use in one expression (3.8+)
annotated count: int = 0 type hint, not enforced at run time
delete del x, del xs[0], del d["k"] remove a name, an item or a key
first, *middle, last = [10, 20, 30, 40]
a = b = [] # one list, two names
a.append(1)
x, y = 1, 2
x, y = y, x
print(first, middle, last, b, x, y)
if (n := len(middle)) >= 2:
print(f"{n} items in the middle")
Output
10 [20, 30] 40 [1] 2 1
2 items in the middle
Group Operators Example Result
arithmetic + - * / // % ** 7 / 2, 7 // 2, 7 % 2, 2 ** 10 3.5, 3, 1, 1024
matrix multiply @ a @ b (NumPy)
comparison == != < <= > >= 1 < 2 < 3 True (chained)
identity is, is not x is None same object
membership in, not in 3 in [1, 2, 3] True
logical and, or, not 0 or 5 5 (returns an operand)
bitwise & | ^ ~ << >> 6 & 3, 6 | 3, 6 ^ 3, ~6, 1 << 4 2, 7, 5, -7, 16
conditional a if cond else b "pos" if x > 0 else "neg"
assignment expression := (n := 10) + 1 11
set operators | & - ^ {1, 2} | {2, 3} {1, 2, 3}
dict merge |, |= {"a": 1} | {"b": 2} right side wins on clashes
sequence +, * [0] * 3, "ab" + "c" [0, 0, 0], 'abc'
Level Operators Note
1 (...), [...], {...}, literals grouping and displays
2 x[i], x[a:b], f(...), x.attr subscript, slice, call, attribute
3 await x
4 ** right to left: 2 ** 3 ** 2 == 512; binds tighter than unary minus on its left
5 +x, -x, ~x -2 ** 2 == -4
6 *, @, /, //, % left to right
7 +, -
8 <<, >>
9 &
10 ^
11 |
12 in, not in, is, is not, <, <=, >, >=, !=, == all chain: a < b == c
13 not x not a == b is not (a == b)
14 and
15 or a or b and c is a or (b and c)
16 x if c else y
17 lambda
18 := lowest; usually needs parentheses
print(-2 ** 2, (-2) ** 2, 2 ** 3 ** 2, 2 ** -1)
print(1 + 2 * 3, (1 + 2) * 3, 10 - 4 - 3, 2 * 3 % 4)
print(1 < 2 < 3, 1 < 3 > 2, (1 < 2) < 3, not 1 == 2)
x, y = 5, 3
print(x > 1 & y < 2, (x > 1) & (y < 2)) # & binds tighter than >
print(True or False and False, (True or False) and False)
Output
-4 4 512 0.5
7 9 3 2
True True True True
True False
True False
Falsy Truthy
False, None True
0, 0.0, 0j, Decimal(0), Fraction(0) any other number, negatives too
"", b"" any non-empty string: " ", "0", "False"
[], (), {}, set(), range(0) any non-empty container
objects whose __bool__ returns False or __len__ returns 0 other objects (by default)
Expression Returns Example
a or b a if a is truthy, else b "" or "n/a" → 'n/a'
a and b a if a is falsy, else b [] and 1 → []
not a always a bool not [] → True
any(it) True if one item is truthy (stops early) any(x > 3 for x in xs)
all(it) True if every item is truthy; True for empty all([]) → True
print(bool(0.0), bool("0"), bool([]), bool([0]), bool(None))
print(0 or "default", "set" or "default", [] and "never", 3 and 4)
print(any([0, "", None]), all([1, "a", [0]]), all([]), any([]))
def check(label):
print("checked", label)
return False
result = check("a") and check("b") # short-circuit: b is never called
Output
False True False True False
default set [] 4
False True True False
checked a
Call Result Note
int("42"), int(" 42\n") 42 surrounding whitespace is ignored
int("1_000") 1000 underscores between digits are allowed
int("3.7") ValueError use int(float("3.7")) → 3
int(3.7), int(-3.7) 3, -3 truncates toward zero
int("ff", 16), int("0b101", 0) 255, 5 base 0 reads the prefix
float("1e-3"), float("inf"), float("nan") 0.001, inf, nan
float("1,5") ValueError replace the comma first
str(3.0), repr("a") '3.0', "'a'" repr shows quotes and escapes
bool("False") True any non-empty string is truthy
ord("A"), chr(65) 65, 'A' code point ↔ character
list("abc"), tuple([1, 2]), set([1, 1, 2]) ['a', 'b', 'c'], (1, 2), {1, 2} from any iterable
dict([("a", 1)]), dict(zip(keys, values)) {'a': 1} from pairs
int(True), float(False) 1, 0.0
bin(10), oct(10), hex(255) '0b1010', '0o12', '0xff' strings with prefix
print(int("ff", 16), int("0o17", 0), int(float("3.7")), int(-3.7))
print(float(" 2.5 "), str(1 / 3), repr("tab\t"))
print(int("3.7"))
Output
255 15 3 -3
2.5 0.3333333333333333 'tab\t'
ValueError: invalid literal for int() with base 10: '3.7'
Type Use for Exact? Create
int counts, ids, money in cents yes, any size 42, int("42")
float measurements, science, ML no (binary) 0.1, float("0.1")
Decimal money, fixed decimal places, legal rounding yes (decimal) Decimal("0.10")
Fraction exact ratios yes (rational) Fraction(1, 3)
complex signals, math no 1 + 2j
from decimal import ROUND_HALF_UP, Decimal, getcontext
from fractions import Fraction
print(0.1 + 0.2, 0.1 + 0.2 == 0.3) # binary floats are approximate
print(Decimal("0.1") + Decimal("0.2"), Decimal(0.1)) # always build from a string
price = Decimal("19.99") * 3 * Decimal("0.925")
print(price, price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
print(getcontext().prec) # 28 significant digits by default
print(Fraction(1, 3) + Fraction(1, 6), Fraction("0.75"))
print(Fraction(0.1).limit_denominator(100)) # nearest simple fraction
print(2**100, (2**100).bit_length(), 10**20 // 7) # ints never overflow
Output
0.30000000000000004 False
0.3 0.1000000000000000055511151231257827021181583404541015625
55.47225 55.47
28
1/2 3/4
1/10
1267650600228229401496703205376 101 14285714285714285714
Call 2.5 -2.5 2.675 (to 2 places) Rule
round(x) / round(x, 2) 2 -2 2.67 half to even, on the binary value
math.floor(x) 2 -3 toward minus infinity
math.ceil(x) 3 -2 toward plus infinity
math.trunc(x), int(x) 2 -2 toward zero
x // 1 2.0 -3.0 floor, keeps the float type
f"{x:.0f}" / f"{x:.2f}" '2' '-2' '2.67' same as round
Decimal(str(x)).quantize(Decimal("0.01"), ROUND_HALF_UP) 2.68 school rounding
round(x, -2) to hundreds: round(1250, -2) → 1200
import math
from decimal import ROUND_HALF_EVEN, ROUND_HALF_UP, Decimal
print([round(x) for x in (0.5, 1.5, 2.5, 3.5)], round(2.675, 2))
print(math.floor(-2.5), math.ceil(-2.5), math.trunc(-2.5), int(-2.5), -2.5 // 1)
cents = Decimal("0.01")
for text in ("2.675", "2.665"):
d = Decimal(text)
print(text, d.quantize(cents, ROUND_HALF_UP), d.quantize(cents, ROUND_HALF_EVEN))
print(round(1250, -2), round(1350, -2), round(1234.5678, -1))
Output
[0, 2, 2, 4] 2.67
-3 -2 -2 -2 -3.0
2.675 2.68 2.68
2.665 2.67 2.66
1200 1400 1230.0
Task Use Example
compare two floats math.isclose(a, b, rel_tol=1e-9)
compare with 0 math.isclose(x, 0, abs_tol=1e-9) relative tolerance alone never matches 0
test NaN math.isnan(x) (never x == nan) nan != nan
test infinity math.isinf(x), math.isfinite(x)
exactly rounded sum math.fsum(xs) sum() of floats is compensated since 3.12, fsum is exact
whole-number float? x.is_integer() (3.0).is_integer() → True
integer square root math.isqrt(n) math.isqrt(17) → 4
power with modulus pow(base, exp, mod) fast modular arithmetic
gcd, lcm math.gcd(a, b), math.lcm(a, b)
product, combinations math.prod(xs), math.comb(n, k), math.perm(n, k)
largest float, epsilon sys.float_info.max, sys.float_info.epsilon
import math
nan = float("nan")
print(nan == nan, math.isnan(nan), math.inf > 1e308, -math.inf < 0)
print(0.1 + 0.1 + 0.1, sum([1e100, 1.0, -1e100]), math.fsum([0.1] * 10))
print(math.isclose(1e-12, 0), math.isclose(1e-12, 0, abs_tol=1e-9))
print(math.isqrt(17), pow(3, 200, 7), math.gcd(12, 18), math.lcm(4, 6), math.comb(5, 2))
Output
False True True True
0.30000000000000004 1.0 1.0
False True
4 2 6 12 10
Task Write Avoid
test for None x is None, x is not None x == None (ruff E711)
optional parameter def f(items=None): then if items is None: items = [] def f(items=[]):
default only for None value if value is not None else 0 value or 0 (also replaces 0, "")
type hint def find(key: str) -> int | None:
function without return returns None result = xs.sort() (gives None)
missing dict key d.get("k") → None d["k"] raises KeyError
def first_negative(values: list[float]) -> float | None:
for v in values:
if v < 0:
return v
return None # explicit: "not found"
found = first_negative([3, 0, 2])
print(found, found is None, first_negative([1, -2, -5]))
count = 0
print(count or 10, count if count is not None else 10) # `or` replaces the real 0
print([3, 1, 2].sort()) # in-place methods return None
Output
None True -2
10 0
None

if, elif, else and conditional expressions

Section titled “if, elif, else and conditional expressions”
def grade(score: float) -> str:
if score >= 90:
return "A"
elif score >= 75:
return "B"
elif score >= 50:
return "C"
else:
return "F"
temps = [18.5, 22.0, 25.5]
print([grade(s) for s in (95, 75, 49.9)])
print(["hot" if t > 24 else "ok" if t >= 19 else "cold" for t in temps])
print(max(0, min(100, 120))) # clamp without if
Output
['A', 'B', 'F']
['cold', 'ok', 'hot']
100
Pattern Syntax Matches
literal 200, "ok", None, True an equal value (None, True, False by identity)
or "a" | "b" any alternative
wildcard _ anything; binds nothing
capture name anything; binds it to name
value Color.RED, http.HTTPStatus.OK equal to a dotted constant
sequence [a, b], (a, b, *rest), [] any sequence of that length (list, tuple, range, deque), except str, bytes and bytearray
mapping {"type": "click", "x": x, **rest} a mapping with these keys; extra keys allowed
class Point(x=0, y=y), Point(0, y), int(n) an instance with these attributes
as [*_] as items, (int() | float()) as n binds the matched sub-value
guard case [x, y] if x == y: the pattern and then the condition
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
def describe(event: object) -> str:
match event:
case {"type": "click", "pos": (x, y)}:
return f"click at {x},{y}"
case {"type": "key", "key": str(key)} if len(key) == 1:
return f"key {key!r}"
case Point(x=0, y=0):
return "origin"
case Point(x, y) if x == y:
return f"diagonal {x}"
case [first, *rest]:
return f"list of {1 + len(rest)} starting {first}"
case int() | float() as n if n < 0:
return f"negative {n}"
case None:
return "nothing"
case _:
return f"unknown {type(event).__name__}"
events = [{"type": "click", "pos": (3, 4)}, {"type": "key", "key": "q"}, Point(0, 0),
Point(2, 2), [5, 6, 7], -1.5, None, "text"]
for e in events:
print(describe(e))
Output
click at 3,4
key 'q'
origin
diagonal 2
list of 3 starting 5
negative -1.5
nothing
unknown str
Form Example Note
over items for x in xs: any iterable
with index for i, x in enumerate(xs, start=1):
in parallel for a, b in zip(xs, ys, strict=True): strict=True (3.10+) raises on unequal lengths
over a dict for k, v in d.items(): for k in d: gives keys
counting for i in range(start, stop, step): stop is excluded
backward for x in reversed(xs):
sorted for x in sorted(xs, key=len, reverse=True):
while while cond: check a condition each pass
loop and a half while True: … if done: break
read until empty while (chunk := f.read(4096)): walrus
skip continue next iteration
stop break leaves the innermost loop only
no-break branch for ...: ... else: runs if the loop did not break
range(...) Values
range(5) 0 1 2 3 4
range(2, 6) 2 3 4 5
range(0, 10, 3) 0 3 6 9
range(5, 0, -1) 5 4 3 2 1
range(0), range(5, 2) nothing
for n in [9, 15, 7, 21]:
if n % 7 == 0:
print("first multiple of 7:", n)
break
else:
print("none found")
for i, (name, score) in enumerate(zip(["ana", "ben"], [81, 67], strict=True), start=1):
print(i, name, score)
n, steps = 27, 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
steps += 1
print("steps:", steps, list(range(10, 0, -3)))
Output
first multiple of 7: 7
1 ana 81
2 ben 67
steps: 111 [10, 7, 4, 1]
Form Syntax Result
list with a filter [f(x) for x in xs if x > 0] if at the end filters
choose a value per item [x if x > 0 else 0 for x in xs] if ... else at the front
dict, set, generator {k: v for k, v in pairs}, {x for x in xs}, (x for x in xs)

Nested loops, flattening, the walrus and the rules of thumb are on the comprehensions section.

Statement Use
pass an empty block
... an empty body in stubs and protocols
assert cond, "message" developer checks; removed by python -O
del name unbind a name or remove an item
global x, nonlocal x rebind a name in an outer scope (functions page)
with ... as f: context manager (decorators and context managers)
try / except / else / finally errors (errors and debugging)
type Alias = int | str type alias statement (3.12+)
if __name__ == "__main__": run code only when the file is a script
Trap Symptom Fix
0.1 + 0.2 == 0.3 False math.isclose; Decimal for money
round(2.5) 2, not 3 Decimal.quantize(..., ROUND_HALF_UP)
round(2.675, 2) 2.67 the float is stored as 2.67499...; use Decimal("2.675")
Decimal(0.1) a 55-digit value build from a string: Decimal("0.1")
-7 // 2, -7 % 2 -4, 1 floor division; use math.trunc(a / b) to truncate
-2 ** 2 -4 (-2) ** 2
x == 1 or 2 always truthy x in (1, 2)
bool("False") True compare the text: s.lower() == "true"
value or default replaces a real 0 or "" value if value is not None else default
x == None works but is wrong style; breaks with NumPy x is None
is with numbers or strings a is b can be False for equal values use ==; keep is for None, True, False
(1) an int, not a tuple (1,)
{} an empty dict, not a set set()
a = b = [] changing a changes b a, b = [], []
x > 1 & y < 2 (pandas masks) parsed as x > (1 & y) < 2: wrong rows or an error (x > 1) & (y < 2)
nan == nan False; nan in checks also mislead math.isnan(x)
case RED: in match captures everything; SyntaxError if not last use a dotted name Color.RED or a guard
for ... else else runs when the loop did not break rename mentally to “nobreak”
int("1" * 5000) ValueError: Exceeds the limit (4300 digits) sys.set_int_max_str_digits(0) if you trust the input
xs = xs.sort() xs becomes None xs.sort() or xs = sorted(xs)
zip(a, b) with unequal lengths silently drops the extra items zip(a, b, strict=True)
True + True 2 bool is an int; check type(x) is bool if it matters

Text in Python: literals and escapes, slicing, the str methods you use every day, f-strings with the complete format-spec mini-language, and the step from str to bytes (encodings, Unicode normalization). Every runnable block is checked against its output.

I want to… Use… Example
put a value in text f-string f"{name} has {n} items"
show 2 decimals :.2f f"{3.14159:.2f}" → 3.14
add thousands separators :, or :_ f"{1234567:,}" → 1,234,567
show a percentage :.1% f"{0.256:.1%}" → 25.6%
pad a number with zeros :05d or str.zfill f"{42:05d}" → 00042
align in a column :<10, :>10, :^10 f"{'id':>6}" → ' id'
choose the width at run time nested braces f"{x:>{width}.{prec}f}"
debug-print a name and its value = f"{total=}" → total=42
show quotes and escapes !r or repr() f"{s!r}" → 'a\tb'
format a date strftime codes in the spec f"{d:%Y-%m-%d}"
show hex or binary :x, :#x, :08b f"{255:#x}" → 0xff
use scientific notation :.2e f"{12345:.2e}" → 1.23e+04
print a literal brace double it f"{{x}}" → {x}
remove whitespace at both ends s.strip() " a ".strip() → 'a'
remove a known prefix or suffix removeprefix, removesuffix "v1.2".removeprefix("v")
split on whitespace s.split() "a b\tc".split() → ['a', 'b', 'c']
split on a delimiter, once s.split(sep, 1) or partition "k=v=w".split("=", 1)
split into lines s.splitlines() handles \n and \r\n
join a list into text sep.join(items) ", ".join(["a", "b"])
join numbers sep.join(map(str, nums)) "-".join(map(str, [1, 2]))
test the start or end startswith / endswith (a tuple works) f.endswith((".csv", ".tsv"))
find a substring in, find (−1), index (raises) "py" in "python"
count occurrences s.count(sub) "banana".count("a") → 3
replace text s.replace(old, new, count) "a-b-c".replace("-", "", 1)
replace or delete many characters str.maketrans + translate see Replace and translate
compare without case a.casefold() == b.casefold() handles ß and other letters
reverse a string s[::-1] "abc"[::-1] → 'cba'
check that text is a whole number s.isdecimal() "42".isdecimal() → True
repeat text * "-" * 20
build text in a loop append to a list, then "".join(parts) faster than += in a loop
turn text into bytes s.encode("utf-8") "é".encode() → b'\xc3\xa9'
turn bytes into text b.decode("utf-8") errors="replace" to keep going
read an old file open(path, encoding="latin-1") see Encodings
compare accented text reliably unicodedata.normalize("NFC", s) "é" vs "e\u0301"
wrap long text textwrap.fill(s, width=60) also textwrap.shorten, dedent
Form Example Note
single or double quotes 'it', "it's" same type; pick the one that avoids escapes
triple quotes """line 1\nline 2""" keeps line breaks; docstrings
raw string r"C:\new\data", r"\d+" backslashes stay literal; for regex and Windows paths
f-string f"{x}", rf"\d{{{n}}}" combine with r
implicit concatenation ("part one " "part two") adjacent literals join at compile time
bytes b"abc", rb"\x00" not str
Escape Meaning Escape Meaning
\n line feed \t tab
\r carriage return \\ one backslash
\', \" quote \0 null character
\x41 char by 2 hex digits (A) \u00e9 char by 4 hex digits (é)
\U0001F600 char by 8 hex digits \N{SNOWMAN} char by Unicode name
Expression s = "Python" Note
s[0], s[-1] 'P', 'n' negative counts from the end
s[1:4] 'yth' start included, stop excluded
s[:2], s[2:] 'Py', 'thon' s[:i] + s[i:] == s
s[-3:] 'hon' last 3
s[::2] 'Pto' every 2nd character
s[::-1] 'nohtyP' reversed
s[10:] '' slices never raise
s[10] IndexError indexes do
len(s) 6 code points, not bytes
s = "Python"
print(s[0], s[-1], s[1:4], s[:2], s[2:], s[-3:], s[::2], s[::-1])
print(repr(s[10:]), repr(s[4:1]), s[:2] + s[2:] == s)
code = "S01-2024-0042"
store, year, number = code.split("-")
print(store, int(year), int(number), code[-4:])
Output
P n yth Py thon hon Pto nohtyP
'' '' True
S01 2024 42 0042

Strings are immutable: every method returns a new string.

Method "hello WORLD" → Note
lower() 'hello world'
upper() 'HELLO WORLD'
title() 'Hello World' "o'brien".title() → "O'Brien"
capitalize() 'Hello world' the rest goes lower case
swapcase() 'HELLO world'
casefold() 'hello world' stronger lower() for comparisons: "ß" → "ss"
Method Example Result
strip(), lstrip(), rstrip() " a \n".strip() 'a'
strip(chars) "--a-b--".strip("-") 'a-b' (a set of characters, not a prefix)
removeprefix(p), removesuffix(s) "report.csv".removesuffix(".csv") 'report'
center(w, fill) "hi".center(6, "*") '**hi**'
ljust(w), rjust(w) "7".rjust(3) ' 7'
zfill(w) "-42".zfill(5) '-0042' (keeps the sign)
expandtabs(n) "a\tb".expandtabs(4) 'a b'
Method Example Result
sub in s "ell" in "hello" True
find(sub), rfind(sub) "hello".find("l"), "hello".find("z") 2, -1
index(sub), rindex(sub) "hello".index("z") ValueError
count(sub) "banana".count("an") 2 (no overlaps)
startswith(p), endswith(s) "a.csv".endswith((".csv", ".tsv")) True
isdecimal() "042", "4.2", "-4" True, False, False
isdigit(), isnumeric() "²".isdigit(), "½".isnumeric() True, True (wider than decimal)
isalpha(), isalnum() "abc", "abc1" True, True
isspace() " \t\n" True ("" is False)
isupper(), islower(), istitle() "ABC1" True for isupper
isascii() "café" False
isidentifier() "total_2" True (valid variable name)
Method Example Result
split() " a b\tc\n".split() ['a', 'b', 'c'] (runs of whitespace, ends dropped)
split(sep) "a,b,,c".split(",") ['a', 'b', '', 'c'] (empty fields kept)
split(sep, maxsplit) "k=v=w".split("=", 1) ['k', 'v=w']
rsplit(sep, maxsplit) "a.b.c".rsplit(".", 1) ['a.b', 'c']
splitlines() "a\nb\r\n".splitlines() ['a', 'b']
partition(sep) "key: val".partition(": ") ('key', ': ', 'val') (always 3 parts)
rpartition(sep) "a/b/c".rpartition("/") ('a/b', '/', 'c')
sep.join(iterable) "-".join(["a", "b"]) 'a-b' (items must be str)
line = " 2024-05-01, S01 , 458.94 , "
fields = [f.strip() for f in line.split(",")]
print(fields)
print("a,b,,c".split(","), "k=v=w".split("=", 1), "a.b.c".rsplit(".", 1))
print("Host: example.org:8080".partition(": "), "a\nb\r\nc".splitlines())
print("-".join(["2024", "05", "01"]), ", ".join(map(str, [1, 2.5, None])))
Output
['2024-05-01', 'S01', '458.94', '']
['a', 'b', '', 'c'] ['k', 'v=w'] ['a.b', 'c']
('Host', ': ', 'example.org:8080') ['a', 'b', 'c']
2024-05-01 1, 2.5, None
print("2024/05/01".replace("/", "-"), "a-b-c".replace("-", "", 1))
table = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "ß": "ss"})
print("Grüße aus Köln".translate(table))
drop_punct = str.maketrans("", "", ",.;!?") # third argument: delete these
print("Hi, there! Ok?".translate(drop_punct))
print(" ".join("too many spaces ".split())) # collapse whitespace
Output
2024-05-01 ab-c
Gruesse aus Koeln
Hi there Ok
too many spaces
from pathlib import Path
for raw in Path("data/messy_names.txt").read_text(encoding="utf-8").splitlines()[:4]:
clean = " ".join(raw.split()).title()
print(f"{raw!r:28} -> {clean}")
Output
' josé GARCÍA ' -> José García
"ZOË o'brien" -> Zoë O'Brien
'françois dupont' -> François Dupont
'Björk Guðmundsdóttir ' -> Björk Guðmundsdóttir
Feature Example Result
any expression f"{2 * 21}", f"{name.upper()}" '42'
format spec after : f"{pi:.3f}" '3.142'
conversion !r, !s, !a f"{s!r}" repr(s), str(s), ascii(s)
conversion and spec f"{s!r:>12}" conversion first, then the spec
self-documenting = f"{x=}", f"{x = }", f"{x=:.2f}" 'x=3.14159'; spaces kept
nested spec f"{x:{w}.{p}f}" width and precision from variables
literal braces f"{{", f"}}" '{', '}'
same quotes inside (3.12+) f"{d["key"]}" earlier versions need the other quote type
multi-line f"""{a}\n{b}"""
date and time f"{when:%Y-%m-%d %H:%M}" calls when.__format__
the format() built-in format(0.5, ".0%") '50%'; same spec language
str.format "{:>8}".format(x) for templates kept as data
name, total, ratio = "Ana", 1234.5, 0.0731
width, prec = 12, 1
print(f"{name!r} {name!s} {'café'!a}")
print(f"{total=}", f"{total = :,.2f}", f"{ratio * 100 = :.1f}")
print(f"[{total:>{width}.{prec}f}]", f"[{name:^{width}}]", f"{{{name}}}")
order = {"id": "O000001", "qty": 3}
print(f"{order['id']} x{order['qty']}", f"{len(order)=}")
Output
'Ana' Ana 'caf\xe9'
total=1234.5 total = 1,234.50 ratio * 100 = 7.3
[ 1234.5] [ Ana ] {Ana}
O000001 x3 len(order)=2

{value:[[fill]align][sign][z][#][0][width][grouping][.precision][type]}

Field Values Meaning Example Result
fill any character pad character (needs an align) f"{7:*>4}" '***7'
align < > ^ = left, right, center, pad after the sign f"{-7:=5}" '- 7'
sign + - space always, negatives only (default), space for positives f"{7:+}", f"{7: }" '+7', ' 7'
z z show -0.0 as 0.0 (3.11+) f"{-0.001:z.1f}" '0.0'
# # prefix 0x/0o/0b; keep the . with g f"{255:#x}" '0xff'
0 0 zero padding, sign-aware f"{-7:05}" '-0007'
width integer minimum total width f"{'ab':5}|" 'ab |'
grouping , _ thousands separator (_ every 4 digits for x, b) f"{10**6:_}" '1_000_000'
precision .n digits after the point (f, e, %), significant digits (g), max chars (s) f"{'abcdef':.3}" 'abc'
type see below presentation f"{0.5:%}" '50.000000%'

Default alignment: numbers align right, strings align left.

Type For Meaning f"{x:...}" Result
s str string (default) f"{'a':s}" 'a'
d int decimal integer f"{42:d}" '42'
b, o, x, X int binary, octal, hex, upper hex f"{255:X}" 'FF'
c int character for the code point f"{65:c}" 'A'
n number like d/g, with the locale’s separators f"{1234:n}" '1234' (C locale)
f, F number fixed point (default precision 6) f"{2/3:f}" '0.666667'
e, E number scientific f"{12345.678:.2e}" '1.23e+04'
g, G number general: fixed or scientific, trailing zeros dropped f"{0.00001234:.3g}" '1.23e-05'
% number times 100, fixed, then % f"{0.1234:.1%}" '12.3%'
none number like g, but at least one digit after the point f"{1e16}" '1e+16'
x = 1234.5678
for spec in ["", ".2f", ",.2f", "_.1f", ">12.2f", "<12.1f", "^12.0f", "*^12,.0f",
"012.2f", "+.1f", " .1f", ".3e", ".3g", ".2%", ".0f"]:
print(f"{spec!r:12} [{x:{spec}}]")
Output
'' [1234.5678]
'.2f' [1234.57]
',.2f' [1,234.57]
'_.1f' [1_234.6]
'>12.2f' [ 1234.57]
'<12.1f' [1234.6 ]
'^12.0f' [ 1235 ]
'*^12,.0f' [***1,235****]
'012.2f' [000001234.57]
'+.1f' [+1234.6]
' .1f' [ 1234.6]
'.3e' [1.235e+03]
'.3g' [1.23e+03]
'.2%' [123456.78%]
'.0f' [1235]
n = 255
for spec in ["d", "5d", "05d", "+d", ",d", "b", "08b", "#b", "o", "#o", "x", "#06x",
"X", "_b", "c", "<6", "^6", "=+6"]:
print(f"{spec!r:7} [{n:{spec}}]")
Output
'd' [255]
'5d' [ 255]
'05d' [00255]
'+d' [+255]
',d' [255]
'b' [11111111]
'08b' [11111111]
'#b' [0b11111111]
'o' [377]
'#o' [0o377]
'x' [ff]
'#06x' [0x00ff]
'X' [FF]
'_b' [1111_1111]
'c' [ÿ]
'<6' [255 ]
'^6' [ 255 ]
'=+6' [+ 255]
word, neg = "data", -0.0004
for spec in ["", "10", ">10", "^10", "-^10", ".2", ">8.3"]:
print(f"{spec!r:7} [{word:{spec}}]")
print(f"[{neg:.2f}] [{neg:z.2f}] [{-42:=8}] [{-42:08}] [{42:#010b}]")
Output
'' [data]
'10' [data ]
'>10' [ data]
'^10' [ data ]
'-^10' [---data---]
'.2' [da]
'>8.3' [ dat]
[-0.00] [0.00] [- 42] [-0000042] [0b00101010]
rows = [
("Chicago", 2850, 458.94),
("Minneapolis", 1950, 1234.5),
("Detroit", 1420, 87.0),
]
print(f"{'city':<12}{'size_sqm':>9}{'revenue':>11}")
print("-" * 32)
for city, size, revenue in rows:
print(f"{city:<12}{size:>9,}{revenue:>11,.2f}")
print(f"{'total':<12}{sum(r[1] for r in rows):>9,}{sum(r[2] for r in rows):>11,.2f}")
Output
city size_sqm revenue
--------------------------------
Chicago 2,850 458.94
Minneapolis 1,950 1,234.50
Detroit 1,420 87.00
total 6,220 1,780.44
Code Meaning Example (2024-05-01 08:04:09, a Wednesday)
%Y, %y year 2024, 24
%m, %d month, day (zero-padded) 05, 01
%H, %I, %p hour 24h, hour 12h, AM/PM 08, 08, AM
%M, %S, %f minute, second, microsecond 04, 09, 000000
%a, %A weekday short, full Wed, Wednesday
%b, %B month short, full May, May
%j, %U day of year, week of year 122, 17
%z, %Z UTC offset, zone name empty for naive datetimes
%% a literal %
from datetime import datetime
when = datetime(2024, 5, 1, 8, 4, 9)
print(f"{when:%Y-%m-%d %H:%M}", f"{when:%a %d %b %Y}", f"{when:%I:%M %p}")
print(when.isoformat(), when.strftime("%j"))
print(datetime.strptime("01/05/2024", "%d/%m/%Y")) # parse: text -> datetime
Output
2024-05-01 08:04 Wed 01 May 2024 08:04 AM
2024-05-01T08:04:09 122
2024-05-01 00:00:00
name, n = "Ana", 3
print("%s has %d items, %.1f%%" % (name, n, 12.34)) # printf style (logging uses it)
print("{} has {:03d} items".format(name, n)) # str.format: templates kept as data
print("{name} has {n} items".format_map({"name": name, "n": n}))
Output
Ana has 3 items, 12.3%
Ana has 003 items
Ana has 3 items
Style Use it for
f-string almost everything
str.format / format_map templates stored in config or translation files
% formatting logging calls: log.info("loaded %d rows", n) (formats only if the level is on)
string.Template user-supplied templates: Template("Hi $name").substitute(name="Ana") (no code runs)
Concept str bytes
holds Unicode code points integers 0–255
literal "café" b"caf\xc3\xa9"
length of café 4 5 in UTF-8
one item "café"[0] → 'c' b"caf"[0] → 99 (an int)
convert s.encode("utf-8") b.decode("utf-8")
read from a file open(p, encoding="utf-8") open(p, "rb")
Encoding Covers Note
utf-8 all of Unicode, 1–4 bytes per char the default to choose; ASCII-compatible
utf-8-sig UTF-8 with a BOM Excel CSV exports; strips the BOM on read
latin-1 (iso-8859-1) 256 Western European chars decodes any bytes without error (maybe wrongly)
cp1252 Windows Western European like latin-1, plus € and smart quotes
ascii 128 chars fails on any accent
utf-16 all of Unicode, 2 or 4 bytes some Windows tools
errors= On a bad byte or char Example result
"strict" (default) raise UnicodeDecodeError / UnicodeEncodeError
"replace" � on decode, ? on encode 'caf�'
"ignore" drop it data loss; avoid
"backslashreplace" \xff escape keeps the evidence
"surrogateescape" round-trips unknown bytes file names, pipes
text = "Café ☕"
data = text.encode("utf-8")
print(len(text), len(data), data)
print(data.decode("utf-8"), "Café".encode().decode("latin-1")) # wrong codec: mojibake
print(text.encode("ascii", errors="replace"), b"caf\xff".decode("utf-8", "replace"))
print(data[0], data[:3], data.hex(" "), bytes.fromhex("43 61 66"))
print(ord("é"), f"U+{ord('é'):04X}", chr(0x2615), "\N{HOT BEVERAGE}" == "☕")
Output
6 9 b'Caf\xc3\xa9 \xe2\x98\x95'
Café ☕ Café
b'Caf? ?' caf�
67 b'Caf' 43 61 66 c3 a9 20 e2 98 95 b'Caf'
233 U+00E9 ☕ True
from pathlib import Path
raw = Path("data/legacy_latin1.csv").read_bytes()
print(raw.decode("latin-1").splitlines()[1]) # the right codec
print(raw.decode("utf-8")) # strict UTF-8 fails on the first non-UTF-8 byte
Output
SUP01,Café Müller GmbH,Köln,Germany,2015
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 49: invalid continuation byte
import unicodedata
composed, decomposed = "é", "e\u0301" # one code point vs. e + combining accent
print(composed == decomposed, len(composed), len(decomposed))
print(unicodedata.normalize("NFC", decomposed) == composed)
print("Straße".lower(), "Straße".casefold())
print("STRASSE".casefold() == "straße".casefold())
decomposed_name = unicodedata.normalize("NFD", "José Müller")
no_accents = "".join(c for c in decomposed_name if not unicodedata.combining(c))
print(no_accents, unicodedata.name("☕"))
Output
False 1 2
True
straße strasse
True
Jose Muller HOT BEVERAGE
Trap Symptom Fix
strings are immutable s.upper() alone changes nothing s = s.upper()
s[0] = "X" TypeError: 'str' object does not support item assignment "X" + s[1:]
strip("abc") strips any of those characters, not the word removeprefix / removesuffix
"".split(",") [''], not [] s.split(",") if s else []
split(" ") vs split() "a b".split(" ") → ['a', '', 'b'] split() with no argument
"-".join([1, 2]) TypeError: sequence item 0: expected str instance, int found "-".join(map(str, xs))
s += piece in a big loop slow on large text collect a list, then "".join(parts)
isdigit() for numbers True for "²"; False for "-4" and "4.2" try: float(s)
f"{x:.2f}" on a str ValueError: Unknown format code 'f' for object of type 'str' convert first: float(x)
f"{x:,}" with x a Decimal works; with a str it fails format numbers, not text
round in specs f"{2.675:.2f}" → '2.67' Decimal for exact half-up rounding
0 flag with an align f"{7:<05}" → '70000' use 0 padding only with right alignment
!r after the spec f"{x:>8!r}" is a ValueError conversion first: f"{x!r:>8}"
quotes in f-strings before 3.12 SyntaxError for f"{d["k"]}" use the other quote: f"{d['k']}"
open() without encoding platform default (cp1252 on Windows) always pass encoding="utf-8"
UnicodeDecodeError on read the file is not UTF-8 try utf-8-sig, cp1252, latin-1; ask the source
latin-1 “works” on anything silent mojibake (Café) check a few known values after decoding
"é" != "é" one is NFD (e + accent) unicodedata.normalize("NFC", s) on input
lower() for case-insensitive keys "Straße".lower() != "STRASSE".lower() casefold()
len() of an emoji flags and families count as several code points len counts code points, not glyphs
b"abc"[0] 97, not b'a' slice: b"abc"[:1]
str(b"abc") "b'abc'" b.decode()

The built-in containers and the collections module: what each operation costs, how to unpack and copy safely, and every comprehension form. Every runnable block is checked against its output.

I want to… Use… Example
add one item to the end xs.append(x) O(1)
add many items xs.extend(items) or xs += items
insert or remove at the front often collections.deque dq.appendleft(x), dq.popleft()
remove by position xs.pop(i) / del xs[i] xs.pop() removes the last
remove by value xs.remove(x) (first match; ValueError if absent)
sort in place / get a sorted copy xs.sort() / sorted(xs) sorted(xs, key=len, reverse=True)
sort by several keys key returns a tuple sorted(rows, key=lambda r: (r["region"], -r["revenue"]))
find the position of a value xs.index(x) ValueError if absent
test membership fast a set or dict x in seen is O(1)
remove duplicates, keep order list(dict.fromkeys(xs))
remove duplicates, order does not matter set(xs)
get a value with a default d.get(k, default) no KeyError
add a key only if missing d.setdefault(k, default) returns the value
group items into lists defaultdict(list) groups[key].append(item)
count things Counter(items) .most_common(3)
merge two dicts a | b (right wins), a |= b {**a, **b} also works
sort a dict by value sorted(d.items(), key=lambda kv: kv[1]) dict(...) to rebuild
invert a dict {v: k for k, v in d.items()} values must be unique and hashable
loop over keys and values for k, v in d.items():
delete keys while looping loop over list(d) changing size during iteration raises
combine, intersect, subtract sets a | b, a & b, a - b, a ^ b
check a subset a <= b, a.issubset(b)
use a set or list as a dict key frozenset(s), tuple(xs) keys must be hashable
unpack first and rest first, *rest = xs rest is a list
unpack nested data for name, (lat, lon) in places:
copy a flat list xs.copy(), xs[:], list(xs) shallow
copy nested data copy.deepcopy(obj)
make a 2D grid [[0] * cols for _ in range(rows)] never [[0] * cols] * rows
keep the last N items deque(maxlen=N) old items fall off
make a light record type namedtuple or typing.NamedTuple p.x, p._replace(x=1)
layer config defaults and overrides ChainMap(cli, env, defaults) first mapping wins
get the N largest items heapq.nlargest(k, xs, key=...) O(n log k), k = number requested
keep a sorted list as you insert bisect.insort(xs, x)
flatten one level [x for sub in nested for x in sub] or itertools.chain.from_iterable
build a dict from two lists dict(zip(keys, values, strict=True))
transpose a matrix list(zip(*matrix)) rows of tuples
Need Use Why
ordered items, change them, index them list O(1) index and append
a fixed record or a dict key tuple immutable, hashable
lookup by key dict O(1) average get and set
unique items, fast in, set algebra set O(1) average in
a hashable set frozenset dict key, set member
a queue or stack with both ends collections.deque O(1) at both ends
counts per key collections.Counter counting helpers built in
a dict of lists or sets collections.defaultdict no if key not in d
a record with named fields typing.NamedTuple, @dataclass readable attributes
a priority queue heapq on a list O(log n) push and pop
a sorted list bisect on a list O(log n) search
many numbers of one type NumPy array vectorized math, compact memory

n is the container size, k the size of the other argument. “Average” assumes good hashes.

Operation list dict set deque
len(x) O(1) O(1) O(1) O(1)
get by index or key O(1) xs[i] O(1) d[k] — O(n) in the middle, O(1) at ends
set by index or key O(1) O(1) — O(n) in the middle
append at the end O(1) amortized O(1) d[k] = v O(1) add O(1)
add or remove at the front O(n) insert(0, x), pop(0) — — O(1) appendleft, popleft
pop the last O(1) O(1) popitem O(1) pop (arbitrary) O(1)
insert or delete in the middle O(n) O(1) del d[k] O(1) discard O(n)
x in c O(n) O(1) keys O(1) O(n)
iterate O(n) O(n) O(n) O(n)
copy O(n) O(n) O(n) O(n)
sort O(n log n) — — —
slice xs[a:b] O(b − a) — — —
extend / update by k items O(k) O(k) O(k) O(k)
min, max, sum O(n) O(n) O(n) O(n)
union, intersection — | O(n + k) | O(n + k), & O(min(n, k)) —
import time
items = list(range(200_000))
as_set = set(items)
start = time.perf_counter()
for _ in range(200):
found = 199_999 in items # scans the whole list
list_time = time.perf_counter() - start
start = time.perf_counter()
for _ in range(200):
found = 199_999 in as_set # one hash lookup
set_time = time.perf_counter() - start
print("set is faster:", set_time < list_time)
Output
set is faster: True
Method Does Returns
append(x) add one item at the end None
extend(it) add every item of it None
insert(i, x) insert before position i None
pop(), pop(i) remove and return the last or item i the item
remove(x) remove the first x None; ValueError if absent
clear() remove everything None
index(x, start, stop) position of the first x int; ValueError if absent
count(x) number of x int
sort(key=, reverse=) sort in place (stable) None
reverse() reverse in place None
copy() shallow copy new list
xs = [3, 1, 4, 1, 5, 9]
xs.append(2)
xs.extend([6, 5])
xs.insert(0, 0)
print(xs)
print(xs.pop(), xs.pop(0), xs.count(1), xs.index(4), xs) # pop returns the item
xs.remove(1) # first 1 only
print(xs, sorted(xs), sorted(xs, reverse=True), xs[::-1])
xs[1:3] = ["a", "b", "c"] # slice assignment can change the length
del xs[-2:]
print(xs, [0] * 3, [1, 2] + [3])
Output
[0, 3, 1, 4, 1, 5, 9, 2, 6, 5]
5 0 2 2 [3, 1, 4, 1, 5, 9, 2, 6]
[3, 4, 1, 5, 9, 2, 6] [1, 2, 3, 4, 5, 6, 9] [9, 6, 5, 4, 3, 2, 1] [6, 2, 9, 5, 1, 4, 3]
[3, 'a', 'b', 'c', 5, 9] [0, 0, 0] [1, 2, 3]
Fact Example
the comma makes a tuple t = 1, 2 and t = (1,); (1) is an int
immutable, hashable if items are {(0, 0): "origin"}
only two methods t.count(x), t.index(x)
return several values return low, high then lo, hi = f()
a tuple can hold a list t = ([1],); t[0].append(2) works, hash(t) fails
compare item by item (1, 2) < (1, 3); used for multi-key sorts
Operation Example Note
create {"a": 1}, dict(a=1), dict(pairs), dict.fromkeys(keys, 0)
read d["a"] KeyError if missing
read with default d.get("a", 0) None without a default
write d["a"] = 2
write if missing d.setdefault("a", []) returns the stored value
delete del d["a"], d.pop("a", None) pop with a default never raises
last inserted pair d.popitem() LIFO
merge d | other, d |= other, d.update(other) right side wins
views d.keys(), d.values(), d.items() live views; keys and items support set operations
order insertion order (guaranteed since 3.7) re-assigning a key keeps its position
keys any hashable: str, int, tuple, frozenset not list, dict, set
equality {"a": 1, "b": 2} == {"b": 2, "a": 1} True: order does not matter
stock = {"apples": 5, "pears": 0}
stock["kiwis"] = 12
print(stock.get("plums"), stock.get("plums", 0), stock.setdefault("figs", 3))
print(stock.pop("pears"), stock.pop("plums", None), list(stock))
print(stock | {"apples": 7, "limes": 1})
print(sorted(stock.items(), key=lambda kv: kv[1], reverse=True))
print(stock.keys() & {"apples", "limes"}, {v: k for k, v in stock.items()})
for name in list(stock): # copy the keys before deleting
if stock[name] < 5:
del stock[name]
print(stock)
Output
None 0 3
0 None ['apples', 'kiwis', 'figs']
{'apples': 7, 'kiwis': 12, 'figs': 3, 'limes': 1}
[('kiwis', 12), ('apples', 5), ('figs', 3)]
{'apples'} {5: 'apples', 12: 'kiwis', 3: 'figs'}
{'apples': 5, 'kiwis': 12}
Operation Operator Method {1, 2, 3} with {3, 4}
union a | b a.union(b) {1, 2, 3, 4}
intersection a & b a.intersection(b) {3}
difference a - b a.difference(b) {1, 2}
symmetric difference a ^ b a.symmetric_difference(b) {1, 2, 4}
subset, superset a <= b, a >= b issubset, issuperset False, False
proper subset a < b False
no common items a.isdisjoint(b) False
add, remove add(x), remove(x) (KeyError), discard(x) (silent)
in-place update a |= b, a &= b, a -= b update, intersection_update

Methods accept any iterable (a.union([4, 5])); operators need sets on both sides.

seen, dupes = set(), set()
for order_id in ["O1", "O2", "O1", "O3", "O2"]:
(dupes if order_id in seen else seen).add(order_id)
print(sorted(seen), sorted(dupes))
a, b = {1, 2, 3}, {3, 4}
print(a | b, a & b, a - b, a ^ b, {1, 2} <= a, a.isdisjoint({9}))
print(list(dict.fromkeys(["b", "a", "b", "c", "a"]))) # dedupe, keep first-seen order
Output
['O1', 'O2', 'O3'] ['O1', 'O2']
{1, 2, 3, 4} {3} {1, 2} {1, 2, 4} True True
['b', 'a', 'c']
Form Example Result
fixed a, b = (1, 2) counts must match
star first, *rest = [1, 2, 3] rest == [2, 3]
star in the middle head, *mid, tail = "abcd" mid == ['b', 'c']
ignore values _, value = pair, *_, last = xs _ is a convention
nested (x, y), z = (1, 2), 3
in a for for i, (k, v) in enumerate(d.items()):
into a list or tuple [*a, *b], (*a, 0) concatenation of any iterables
into a set {*a, *b}
into a dict {**defaults, **overrides} right side wins
into a call f(*args), f(**kwargs) positional and keyword
transpose list(zip(*rows))
head, *middle, tail = "python"
(lat, lon), name = (41.88, -87.63), "Chicago"
rows = [(1, "a"), (2, "b"), (3, "c")]
ids, letters = zip(*rows) # unzip
defaults, overrides = {"sep": ",", "header": True}, {"sep": ";"}
print(head, middle, tail, lat, name, ids, letters)
print([*ids, *"xy"], {**defaults, **overrides})
Output
p ['y', 't', 'h', 'o'] n 41.88 Chicago (1, 2, 3) ('a', 'b', 'c')
[1, 2, 3, 'x', 'y'] {'sep': ';', 'header': True}
Code Result Inner objects
b = a another name for the same object shared
b = a.copy(), a[:], list(a), dict(a), copy.copy(a) new outer container shared
b = copy.deepcopy(a) new container, new inner objects copied
[[0] * 3] * 2 two references to one inner list shared: a bug
[[0] * 3 for _ in range(2)] two separate inner lists separate
import copy
a = [[1, 2], [3, 4]]
alias, shallow, deep = a, a.copy(), copy.deepcopy(a)
a[0].append(99) # change an inner list
a.append([5]) # change the outer list
print(alias, shallow, deep, sep="\n")
grid_bad = [[0] * 3] * 2
grid_ok = [[0] * 3 for _ in range(2)]
grid_bad[0][0] = grid_ok[0][0] = 1
print(grid_bad, grid_ok)
Output
[[1, 2, 99], [3, 4], [5]]
[[1, 2, 99], [3, 4]]
[[1, 2], [3, 4]]
[[1, 0, 0], [1, 0, 0]] [[1, 0, 0], [0, 0, 0]]
Kind Syntax Example result
list [expr for x in it] [x * x for x in range(4)] → [0, 1, 4, 9]
filtered [expr for x in it if cond]
value choice [a if cond else b for x in it]
filter and choice [a if c1 else b for x in it if c2] if/else before for, filter after
nested loops [expr for x in xs for y in ys] same order as nested for statements
nested filter [x for row in m if row for x in row if x] each for can have an if
nested result [[expr for y in ys] for x in xs] a list of lists
dict {k: v for k, v in it}
dict filter {k: v for k, v in d.items() if v}
set {expr for x in it}
generator (expr for x in it) lazy; consumed once
generator as the only argument sum(x for x in it) no extra parentheses
with walrus [y for x in it if (y := f(x))] call f once per item
with enumerate or zip {name: i for i, name in enumerate(names)}
words = ["apple", "Bob", "", "kiwi", "banana", "Anna"]
print([w.lower() for w in words if w])
print([w if len(w) > 3 else "-" for w in words if w])
print({w: len(w) for w in words if w}, {len(w) for w in words})
matrix = [[1, 2, 3], [4, 5, 6]]
print([x for row in matrix for x in row if x % 2]) # flatten and filter
print([[row[i] for row in matrix] for i in range(3)]) # transpose
print([(r, c) for r in "ab" for c in range(2)])
lengths = (len(w) for w in words)
print(max(lengths), sum(lengths)) # max consumed the generator: the sum is 0
print([n for w in words if (n := len(w)) >= 5])
Output
['apple', 'bob', 'kiwi', 'banana', 'anna']
['apple', '-', 'kiwi', 'banana', 'Anna']
{'apple': 5, 'Bob': 3, 'kiwi': 4, 'banana': 6, 'Anna': 4} {0, 3, 4, 5, 6}
[1, 3, 5]
[[1, 4], [2, 5], [3, 6]]
[('a', 0), ('a', 1), ('b', 0), ('b', 1)]
6 0
[5, 6]
Rule Detail
the loop variable does not leak after [x for x in xs], x is not defined (Python 3)
prefer a loop for side effects [print(x) for x in xs] builds a useless list
keep it to one or two clauses three nested for clauses are hard to read; write a loop
a generator for large data sum(x for x in big) does not build a list
map / filter fine with a named function: list(map(str.strip, lines))
import csv
from collections import Counter
with open("data/sales.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
by_region = Counter(row["region"] for row in rows)
print(by_region.most_common(2), by_region.total())
channel = Counter(row["channel"] for row in rows[:100])
print(channel, channel["phone"]) # a missing key counts 0, no KeyError
letters = Counter("mississippi")
letters.update("ss") # add counts
letters.subtract({"i": 4}) # counts can go to 0 or below
print(letters.most_common(3), +letters) # unary + drops counts <= 0
print(Counter(a=3, b=1) - Counter(a=1, b=2), Counter(a=3) & Counter(a=1, b=2))
Output
[('East', 5396), ('South', 5144)] 20228
Counter({'store': 72, 'online': 28}) 0
[('s', 6), ('p', 2), ('m', 1)] Counter({'s': 6, 'p': 2, 'm': 1})
Counter({'a': 2}) Counter({'a': 1})
from collections import defaultdict
orders = [("S01", 66.49), ("S02", 14.99), ("S01", 19.99), ("S03", 59.99)]
by_store = defaultdict(list) # missing keys start as []
total = defaultdict(float) # missing keys start as 0.0
for store, revenue in orders:
by_store[store].append(revenue)
total[store] += revenue
print(dict(by_store))
print({store: round(amount, 2) for store, amount in total.items()})
tree = defaultdict(lambda: defaultdict(int)) # nested counts
tree["North"]["S01"] += 1
print({k: dict(v) for k, v in tree.items()})
print("S09" in total, total["S09"], "S09" in total) # reading a missing key adds it
Output
{'S01': [66.49, 19.99], 'S02': [14.99], 'S03': [59.99]}
{'S01': 86.48, 'S02': 14.99, 'S03': 59.99}
{'North': {'S01': 1}}
False 0.0 True
from collections import deque
queue = deque(["a", "b"])
queue.append("c") # right end
queue.appendleft("z") # left end
print(queue)
print(queue.popleft(), queue.pop(), queue)
last3 = deque(maxlen=3) # a sliding window
for reading in [21.0, 21.9, 21.4, 21.7, 22.1]:
last3.append(reading)
print(last3, round(sum(last3) / len(last3), 2))
ring = deque(range(5))
ring.rotate(2)
print(ring)
Output
deque(['z', 'a', 'b', 'c'])
z c deque(['a', 'b'])
deque([21.4, 21.7, 22.1], maxlen=3) 21.73
deque([3, 4, 0, 1, 2])

The choice between namedtuple, NamedTuple, @dataclass and TypedDict is on the data containers page.

from collections import namedtuple
from typing import NamedTuple
Point = namedtuple("Point", ["x", "y"], defaults=[0])
class Store(NamedTuple):
store_id: str
city: str
size_sqm: int = 0
p = Point(3)
s = Store("S01", "Chicago", 2850)
print(p, p.x + p.y, p._replace(y=5), Point._fields)
print(s.city, s._asdict(), s[0], tuple(s) == ("S01", "Chicago", 2850))
Output
Point(x=3, y=0) 3 Point(x=3, y=5) ('x', 'y')
Chicago {'store_id': 'S01', 'city': 'Chicago', 'size_sqm': 2850} S01 True
from collections import ChainMap, OrderedDict
defaults = {"sep": ",", "encoding": "utf-8", "header": True}
user = {"sep": ";"}
settings = ChainMap(user, defaults) # look up in user first, then defaults
print(settings["sep"], settings["encoding"], dict(settings))
settings["header"] = False # writes go to the first mapping only
print(user, defaults["header"])
lru = OrderedDict.fromkeys("abc")
lru.move_to_end("a") # mark "a" as recently used
print(list(lru), lru.popitem(last=False)) # pop the oldest
print(OrderedDict(a=1, b=2) == OrderedDict(b=2, a=1), dict(a=1, b=2) == dict(b=2, a=1))
Output
; utf-8 {'sep': ';', 'encoding': 'utf-8', 'header': True}
{'sep': ';', 'header': False} True
['b', 'c', 'a'] ('b', None)
False True
Class Use Note
Counter counts, histograms, top-N most_common, total() (3.10+), + - & |
defaultdict(factory) group or accumulate reading a missing key creates it
deque(maxlen=n) queues, sliding windows, BFS O(1) at both ends, O(n) indexing in the middle
namedtuple / NamedTuple small immutable records tuple behavior: unpacking, indexing
ChainMap layered settings, scopes writes go to the first mapping
OrderedDict move_to_end, popitem(last=False) dict keeps order too; use OrderedDict for reordering and order-sensitive ==
import bisect
import heapq
revenue = [66.49, 14.99, 19.99, 59.99, 104.5, 8.0]
print(heapq.nlargest(2, revenue), heapq.nsmallest(2, revenue))
tasks = []
for priority, name in [(3, "write"), (1, "fix"), (2, "test")]:
heapq.heappush(tasks, (priority, name)) # smallest first
print([heapq.heappop(tasks)[1] for _ in range(len(tasks))])
cutoffs, grades = [50, 75, 90], "FCBA"
print([grades[bisect.bisect(cutoffs, score)] for score in (42, 75, 99)])
Output
[104.5, 66.49] [8.0, 14.99]
['fix', 'test', 'write']
['F', 'B', 'A']
Trap Symptom Fix
xs = xs.sort() xs is None xs.sort() or xs = sorted(xs)
b = a then change b a changes too a.copy(); copy.deepcopy for nested data
[[0] * 3] * 3 changing one row changes all rows [[0] * 3 for _ in range(3)]
def f(xs=[]) the list keeps items between calls xs=None, then create it inside
removing from a list while looping over it items are skipped loop over a copy, or build a new list
changing a dict’s size while looping RuntimeError: dictionary changed size during iteration loop over list(d)
x in big_list in a loop O(n²) total, slow convert to a set once
xs.pop(0) / insert(0, x) in a loop O(n) each deque.popleft() / appendleft()
{} an empty dict set() for an empty set
set order changes between runs for strings sorted(s) before printing or comparing
unhashable key TypeError: unhashable type: 'list' tuple(xs) or frozenset(s)
d[key] on a missing key KeyError d.get(key), defaultdict, or in check
reading a defaultdict silently adds the key use in or .get() to check
dict(zip(a, b)) with different lengths extra items dropped zip(a, b, strict=True)
a generator used twice the second pass is empty make a list, or create the generator again
Counter.subtract can leave 0 and negative counts +counter drops them
t = ([1],) the tuple is immutable, the list is not; hash(t) fails use only immutable items in keys
list.remove(x) removes only the first x [y for y in xs if y != x]
sorted(d) sorts the keys, not the items sorted(d.items(), key=...)

How to define and call functions in Python: every parameter kind, how names are looked up (LEGB), closures, functions as values, key= functions for sorting, functools.partial, recursion and docstrings. Every runnable block is checked against its output.

I want to… Use… Example
define a function def name(params) -> type: def area(w: float, h: float) -> float:
return several values return a tuple, unpack it lo, hi = bounds(xs)
give a parameter a default param=value def load(path, sep=","):
default to a new list or dict None default, then create if items is None: items = []
detect “argument not passed” a sentinel object _MISSING = object()
force keyword arguments * in the signature def f(a, *, verbose=False):
force positional arguments / in the signature def f(x, y, /):
accept any number of positional args *args def total(*amounts):
accept any keyword args **kwargs def tag(name, **attrs):
pass a list as separate arguments * in the call f(*values)
pass a dict as keyword arguments ** in the call f(**options)
forward all arguments *args, **kwargs return func(*args, **kwargs)
change a global variable global name (better: return the value)
change a variable of the enclosing function nonlocal name counters in closures
make a function that remembers state a closure make_counter()
write a tiny inline function lambda args: expr key=lambda r: r["revenue"]
sort by a field sorted(xs, key=...) sorted(rows, key=itemgetter("city"))
sort by two fields, one descending key returns a tuple; negate numbers key=lambda r: (r["region"], -r["revenue"])
sort case-insensitively key=str.casefold sorted(names, key=str.casefold)
get the item with the largest value max(xs, key=...) max(stores, key=lambda s: s["size"])
handle an empty input to min or max default= max([], default=0)
fix some arguments of a function functools.partial parse_eu = partial(parse, dayfirst=True)
apply a function to every item comprehension or map [f(x) for x in xs]
keep items that pass a test comprehension or filter [x for x in xs if ok(x)]
fold a sequence into one value functools.reduce (or a loop) reduce(operator.mul, xs, 1)
pick a function by name a dict of functions (dispatch table) handlers[command](args)
cache results of a pure function @functools.cache see decorators
see a function’s parameters inspect.signature(f) print(inspect.signature(f))
document a function docstring """Return the mean of values."""
read the documentation help(f), f.__doc__
raise the recursion limit sys.setrecursionlimit(n) (with care) prefer a loop
def f(pos_only, /, standard, *args, kw_only, kw_default=1, **kwargs): ...
# ^ before / ^ either ^ extra ^ after * or *args: keyword only
# positional way positional ^ extra keywords
Kind Declared Called as Inside the function
positional-only before / f(1) only the name is private; callers cannot use it
positional or keyword between / and * f(1) or f(x=1)
var-positional *args any extra positional arguments a tuple
keyword-only after * or *args f(verbose=True) only
var-keyword **kwargs any extra keyword arguments a dict
default name=value may be left out value is computed once, at def time
def report(store_id, /, metric, *extra, top=3, **options):
print(store_id, metric, extra, top, options)
report("S01", "revenue")
report("S01", metric="units", top=5)
report("S02", "revenue", "q1", "q2", currency="USD", round_to=2)
Output
S01 revenue () 3 {}
S01 units () 5 {}
S02 revenue ('q1', 'q2') 3 {'currency': 'USD', 'round_to': 2}
def report(store_id, /, metric, *extra, top=3, **options):
print(store_id, metric, extra, top, options)
report(store_id="S01", metric="revenue") # positional-only passed by keyword
Output
TypeError: report() missing 1 required positional argument: 'store_id'
Call rule Example Error if broken
positional arguments come before keyword ones f(1, b=2) SyntaxError: positional argument follows keyword argument
each parameter gets one value f(1, a=1) TypeError: f() got multiple values for argument 'a'
required parameters need a value f() TypeError: f() missing 1 required positional argument: 'a'
no unknown keywords (without **kwargs) f(z=1) TypeError: f() got an unexpected keyword argument 'z'
in a signature, defaults come after required parameters def f(a=1, b): SyntaxError (keyword-only parameters are exempt)
def describe(name, city, size_sqm=0):
return f"{name} in {city}, {size_sqm:,} sqm"
row = ["S01", "Chicago", 2850]
options = {"city": "Detroit", "size_sqm": 1420}
print(describe(*row))
print(describe("S03", **options))
print(*["a", "b", "c"], sep=" | ") # spread a list into print()
Output
S01 in Chicago, 2,850 sqm
S03 in Detroit, 1,420 sqm
a | b | c
def add_bad(item, bucket=[]): # one list, created once at def time
bucket.append(item)
return bucket
def add_good(item, bucket=None):
if bucket is None:
bucket = [] # a new list on every call
bucket.append(item)
return bucket
print(add_bad(1), add_bad(2))
print(add_good(1), add_good(2))
Output
[1, 2] [1, 2]
[1] [2]
_MISSING = object() # a unique sentinel: None may be a valid value
def lookup(d, key, default=_MISSING):
if key in d:
return d[key]
if default is _MISSING:
raise KeyError(key)
return default
print(lookup({"a": None}, "a"), lookup({}, "b", None), lookup({}, "c", 0))
Output
None None 0

Python looks a name up in four scopes, in this order:

Scope Where Example
Local assigned inside the current function (parameters too) total = 0 in the function
Enclosing local names of outer functions a closure’s free variables
Global top level of the module TAX_RATE = 0.2
Built-in the builtins module len, print, max
Rule Detail
assignment makes a name local anywhere in the function body, even after the first read
reading needs no declaration functions can read globals and enclosing names freely
global x assignments to x change the module-level name
nonlocal x assignments change the nearest enclosing function’s x
blocks do not create scopes if, for, with, try leak names (except the as name of an except clause, which is deleted); comprehensions and functions do not
shadowing a built-in list = [1] hides list() for the rest of the module
count = 10
def bump():
count += 1 # assignment makes count local, so the read fails
return count
bump()
Output
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
count = 10
def bump_global():
global count # rebind the module-level name
count += 1
def make_counter():
n = 0
def increment():
nonlocal n # rebind the enclosing function's name
n += 1
return n
return increment
bump_global()
counter = make_counter()
print(count, counter(), counter(), counter())
for i in range(3):
square = i * i
print("after the loop:", i, square) # for loops do not create a scope
Output
11 1 2 3
after the loop: 2 4

A closure is an inner function that remembers names from the enclosing function after that function returns.

def make_scaler(factor):
def scale(x):
return x * factor # factor is a free variable
return scale
to_cents = make_scaler(100)
print(to_cents(4.99), make_scaler(2)(21), to_cents.__closure__[0].cell_contents)
Output
499.0 42 100

Closures capture variables, not values:

late = [lambda: i for i in range(3)] # all three see the final i
bound = [lambda i=i: i for i in range(3)] # a default captures the current i
print([f() for f in late], [f() for f in bound])
Output
[2, 2, 2] [0, 1, 2]
Pattern Use
factory function make configured functions: make_validator(low, high)
counter or accumulator keep state without a class (nonlocal)
decorator wrap a function; see decorators
callback with context button.on_click(make_handler(item))
class instead when state has several fields or methods
import operator
def mean(xs):
return sum(xs) / len(xs)
stats = {"min": min, "max": max, "mean": mean} # dispatch table
values = [21.0, 21.9, 21.4]
print({name: round(f(values), 2) for name, f in stats.items()})
ops = {"+": operator.add, "*": operator.mul}
print(ops["*"](6, 7), mean.__name__, callable(mean), callable(42))
Output
{'min': 21.0, 'max': 21.9, 'mean': 21.43}
42 mean True False
Rule Detail
syntax lambda params: expression
one expression only no statements, no assignments (:= works but hurts reading)
returns the expression no return keyword
use it for short key= and callback arguments
avoid f = lambda x: x + 1; write def f(x): return x + 1 (ruff E731)
Goal Code
by a dict field sorted(rows, key=lambda r: r["revenue"]) or key=itemgetter("revenue")
by an attribute sorted(objs, key=attrgetter("city"))
by several fields key=itemgetter("region", "city") or key=lambda r: (r["region"], r["city"])
mixed directions negate numbers: key=lambda r: (r["region"], -r["revenue"])
mixed directions on text two stable sorts: secondary first, then primary
case-insensitive key=str.casefold
by length, then alphabetically key=lambda s: (len(s), s)
largest value’s key in a dict max(d, key=d.get)
empty input max(xs, default=None)
N largest heapq.nlargest(n, xs, key=...)
a method call as key key=methodcaller("lower")
from operator import itemgetter
stores = [
{"id": "S04", "region": "South", "size": 3100},
{"id": "S01", "region": "North", "size": 2850},
{"id": "S02", "region": "North", "size": 1950},
{"id": "S05", "region": "South", "size": 1950},
]
print([s["id"] for s in sorted(stores, key=itemgetter("size"))]) # stable for ties
print([s["id"] for s in sorted(stores, key=lambda s: (s["region"], -s["size"]))])
print(max(stores, key=itemgetter("size"))["id"], min([], default="none"))
names = ["bob", "Anna", "carl", "al"]
print(sorted(names), sorted(names, key=str.casefold)) # upper case sorts first
print(sorted(names, key=lambda s: (len(s), s)))
counts = {"a": 3, "b": 7, "c": 5}
print(max(counts, key=counts.get))
Output
['S02', 'S05', 'S01', 'S04']
['S01', 'S02', 'S04', 'S05']
S04 none
['Anna', 'al', 'bob', 'carl'] ['al', 'Anna', 'bob', 'carl']
['al', 'bob', 'Anna', 'carl']
b
from functools import partial, reduce
import operator
lines = [" 21.0", "21.9 ", "", " 21.4"]
print(list(map(str.strip, lines)), list(filter(None, map(str.strip, lines))))
print(list(map(operator.add, [1, 2, 3], [10, 20, 30]))) # several iterables
print(reduce(operator.mul, [1, 2, 3, 4], 1)) # ((1 * 1) * 2) * 3 * 4
parse_hex = partial(int, base=16)
print(parse_hex("ff"), parse_hex.func.__name__, parse_hex.keywords)
round2 = partial(round, ndigits=2)
print([round2(x) for x in (3.14159, 2.71828)])
Output
['21.0', '21.9', '', '21.4'] ['21.0', '21.9', '21.4']
[11, 22, 33]
24
255 int {'base': 16}
[3.14, 2.72]
Tool Prefer Note
map(f, xs) [f(x) for x in xs] unless f already exists lazy iterator
filter(pred, xs) [x for x in xs if pred(x)] filter(None, xs) drops falsy items
reduce(f, xs, start) sum, math.prod, max, "".join, or a loop always pass a start value
partial(f, *a, **kw) a lambda when you need to reorder arguments keeps func, args, keywords
operator.itemgetter, attrgetter, methodcaller faster and clearer than tiny lambdas
import sys
from functools import cache
def flatten(items):
"""Yield the leaves of nested lists."""
for item in items:
if isinstance(item, list):
yield from flatten(item) # recursive case
else:
yield item # base case
@cache # remember results: O(n) instead of O(2**n)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(list(flatten([1, [2, [3, [4]], 5]])), fib(80), sys.getrecursionlimit())
Output
[1, 2, 3, 4, 5] 23416728348467685 1000
Rule Detail
base case first a case that returns without calling itself
every call gets closer to the base case smaller input each time
depth limit about 1000 frames by default; RecursionError beyond it
no tail-call optimization deep linear recursion should be a loop
good fits trees, nested JSON, divide and conquer, backtracking
repeated sub-problems @functools.cache
import inspect
def churn_rate(churned: int, total: int, *, as_percent: bool = False) -> float:
"""Return the share of customers who churned.
Args:
churned: Number of customers who left.
total: Number of customers at the start.
as_percent: Return 0-100 instead of 0-1.
Returns:
The churn rate.
Raises:
ValueError: If total is not positive.
"""
if total <= 0:
raise ValueError("total must be positive")
rate = churned / total
return rate * 100 if as_percent else rate
print(churn_rate(30, 200), churn_rate(30, 200, as_percent=True))
print(inspect.signature(churn_rate))
print(churn_rate.__doc__.splitlines()[0], churn_rate.__annotations__["return"])
Output
0.15 15.0
(churned: int, total: int, *, as_percent: bool = False) -> float
Return the share of customers who churned. <class 'float'>
Part Content
first line one sentence in the imperative: “Return …”, “Load …”
Args: each parameter and its meaning (types live in the hints)
Returns: / Yields: what comes back
Raises: exceptions a caller should handle
Example: optional; doctest-style >>> lines
Trap Symptom Fix
mutable default def f(x=[]) the list grows across calls x=None, then if x is None: x = []
default from a call def f(t=time.time()) the value is frozen at def time compute it inside the function
UnboundLocalError assigning a name you also read from an outer scope pass it in and return the new value; or nonlocal / global
lambdas in a loop all return the last value lambda i=i: ... or functools.partial
forgetting return the function returns None return the value; ruff and type checkers help
return inside a loop stops after the first item return after the loop
calling instead of passing key=len() is a TypeError; on_click(f()) runs now pass the function: key=len
sorted(..., key=...) with reverse=True and mixed directions wrong order negate numeric keys, or sort twice (stable)
max([]) ValueError: max() iterable argument is empty max(xs, default=...)
map and filter return iterators printing shows <map object at ...>; second pass is empty wrap in list(...) once
global everywhere hidden coupling, hard tests parameters in, return values out
shadowing built-ins TypeError: 'list' object is not callable rename list, sum, max, id, type variables
deep recursion RecursionError: maximum recursion depth exceeded rewrite as a loop with an explicit stack
*args order def f(*args, x) makes x keyword-only intended; document it
**kwargs typos verbos=True is silently accepted avoid **kwargs when you know the options
f = lambda ... no useful name in tracebacks def f(...)

How for really works, how to produce values on demand with generators, the complete itertools toolbox with the official recipes, and lazy pipelines that process large files in constant memory. Every runnable block is checked against its output.

I want to… Use… Example
get an iterator from an iterable iter(x) it = iter([1, 2])
get the next value next(it), next(it, default) next(it, None) never raises
get the first item that matches next(gen, default) next((x for x in xs if x > 3), None)
produce values lazily a generator function with yield def read_rows(path): ... yield row
write a one-line lazy sequence generator expression (x * x for x in xs)
delegate to another iterable yield from it yield from flatten(child)
take the first n items itertools.islice(it, n) list(islice(rows, 5))
skip the first n items islice(it, n, None) skip a header
process in chunks of n itertools.batched(it, n) (3.12+) for batch in batched(rows, 1000):
loop over consecutive pairs itertools.pairwise(it) for a, b in pairwise(xs):
make a sliding window deque(maxlen=n) or the sliding_window recipe moving averages
chain several iterables itertools.chain(a, b) chain(jan, feb, mar)
flatten one level chain.from_iterable(nested)
count forever itertools.count(start, step) ids
repeat a cycle itertools.cycle(it) round-robin colors
running totals itertools.accumulate(xs) accumulate(xs, max) for running max
group consecutive equal keys itertools.groupby(sorted_it, key) sort by the same key first
take while a condition holds takewhile(pred, it) / dropwhile(pred, it) sorted logs
filter with a mask compress(data, selectors)
all pairs of two lists itertools.product(a, b) grid search
all orderings / subsets of size k permutations(it, k) / combinations(it, k)
zip to the longest input zip_longest(a, b, fillvalue=...)
zip with equal lengths enforced zip(a, b, strict=True)
call a function with unpacked tuples itertools.starmap(f, pairs) starmap(pow, [(2, 3)])
iterate twice over one iterator itertools.tee(it, 2) (or a list)
call a function until a sentinel iter(callable, sentinel) iter(lambda: f.read(4096), b"")
stream a big file line by line for line in f: constant memory
count items of an iterator sum(1 for _ in it) consumes it
make a class iterable __iter__ that yields see iterator classes
type-hint a generator Iterator[int] or Generator[int, None, None] (Generator[int] on 3.13+) from collections.abc import Iterator
peek without losing the item first = next(it) then chain([first], it)
Term Has Example Reusable
iterable __iter__() returning an iterator list, str, dict, range, file yes: each iter() starts fresh
iterator __next__() and __iter__() returning itself iter([1, 2]), map(...), zip(...), file no: consumed once
generator an iterator made by a yield function or (...) expression (x for x in xs) no
sequence __getitem__ and __len__ list, tuple, str, range yes
it = iter(["a", "b"]) # what `for` does first
print(next(it), next(it), next(it, "done"))
nums = [1, 2, 3]
print(iter(nums) is iter(nums), iter(it) is it) # lists give new iterators
for_it = iter(nums) # a for loop, written out by hand
while True:
try:
item = next(for_it)
except StopIteration:
break
print(item, end=" ")
print()
Output
a b done
False True
1 2 3
Built-in Returns Lazy
range, dict.keys() / values() / items() a reusable view or sequence yes, not one-shot
map, filter, zip, enumerate, reversed an iterator yes, one-shot
open(...) a file object (an iterator over lines) yes
sorted, list, tuple a list or tuple no: consumes everything
sum, min, max, any, all, "".join one value consumes (any / all stop early)
def countdown(n):
print("start") # runs at the first next(), not at the call
while n > 0:
yield n # pause here and hand out n
n -= 1
return "liftoff" # becomes StopIteration.value
gen = countdown(3)
print(type(gen).__name__)
print(next(gen), next(gen), next(gen))
try:
next(gen)
except StopIteration as stop:
print("finished:", stop.value)
print(list(countdown(2)), list(gen)) # gen is exhausted
Output
generator
start
3 2 1
finished: liftoff
start
[2, 1] []
Fact Detail
calling a generator function runs nothing; returns a generator object
yield value pauses and hands out value; local state is kept
return value ends the generator; for ignores the value
raise StopIteration inside becomes a RuntimeError (PEP 479); use return
gen.close() raises GeneratorExit at the paused yield; finally blocks run
gen.send(x) resumes and makes yield evaluate to x (coroutine style; rare today)
try / finally / with inside clean-up runs when the generator finishes or is closed

Generator expressions vs list comprehensions

Section titled “Generator expressions vs list comprehensions”
[f(x) for x in xs] (f(x) for x in xs)
result a list in memory a generator
memory O(n) O(1)
reuse, len, indexing yes no
when work happens at once on each next()
use when you need the values several times or need len you aggregate once: sum, max, any, writing to a file
def noisy(x):
print(f"compute {x}")
return x * 10
lazy = (noisy(x) for x in range(5))
print("nothing computed yet")
print(next(lazy), next(lazy))
print(any(noisy(x) > 15 for x in range(5))) # stops at the first True
Output
nothing computed yet
compute 0
compute 1
0 10
compute 0
compute 1
compute 2
True
def flatten(items):
for item in items:
if isinstance(item, (list, tuple)):
yield from flatten(item) # delegate to the inner generator
else:
yield item
def read_all(*sources):
for source in sources:
yield from source # same as: for x in source: yield x
def inner():
yield 1
return "inner result"
def outer():
result = yield from inner() # receives inner's return value
yield result
print(list(flatten([1, [2, (3, [4])], 5])), list(read_all("ab", [1, 2])), list(outer()))
Output
[1, 2, 3, 4, 5] ['a', 'b', 1, 2] [1, 'inner result']

Every iteration and container dunder (__iter__, __next__, __len__, __getitem__, __contains__) is in the dunder methods table.

class Countdown:
"""Iterable: each loop gets a fresh generator."""
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
class Fib:
"""Iterator: one-shot, keeps its own state."""
def __init__(self, limit):
self.a, self.b, self.limit = 0, 1, limit
def __iter__(self):
return self
def __next__(self):
if self.a > self.limit:
raise StopIteration
value = self.a
self.a, self.b = self.b, self.a + self.b
return value
c = Countdown(3)
print(list(c), list(c), list(Fib(30)))
Output
[3, 2, 1] [3, 2, 1] [0, 1, 1, 2, 3, 5, 8, 13, 21]
Function Yields Example Result
count(start=0, step=1) start, start + step, … islice(count(10, 5), 3) 10 15 20
cycle(it) the items again and again islice(cycle("ab"), 5) a b a b a
repeat(x, n) x n times (forever without n) repeat(0, 3) 0 0 0
Function Yields Example Result
accumulate(it, func=add, initial=None) running results accumulate([1, 2, 3, 4]) 1 3 6 10
batched(it, n) (3.12+) tuples of up to n items batched("abcde", 2) ('a','b') ('c','d') ('e',)
chain(*its) items of each iterable in turn chain("ab", [1]) a b 1
chain.from_iterable(its) same, from one iterable of iterables chain.from_iterable([[1], [2, 3]]) 1 2 3
compress(data, selectors) items whose selector is truthy compress("abcd", [1, 0, 1, 0]) a c
dropwhile(pred, it) everything after pred is first false dropwhile(lambda x: x < 3, [1, 4, 1]) 4 1
takewhile(pred, it) items until pred is first false takewhile(lambda x: x < 3, [1, 4, 1]) 1
filterfalse(pred, it) items where pred is false filterfalse(str.isdigit, "a1b2") a b
groupby(it, key=None) (key, group) for each run of equal keys groupby("aabca") a b c a (keys)
islice(it, stop) / islice(it, start, stop, step) a slice of any iterator islice("abcdef", 1, None, 2) b d f
pairwise(it) (3.10+) overlapping pairs pairwise([1, 2, 3]) (1, 2) (2, 3)
starmap(func, it) func(*item) starmap(pow, [(2, 3), (3, 2)]) 8 9
tee(it, n=2) n independent iterators a, b = tee(it) buffers what one has seen and the other has not
zip_longest(*its, fillvalue=None) tuples until the longest ends zip_longest("ab", "x", fillvalue="-") ('a','x') ('b','-')
Function Yields "ABC", k = 2 Count
product(*its, repeat=1) the Cartesian product AA AB AC BA BB BC CA CB CC (with repeat=2) n^k
permutations(it, k) ordered arrangements, no repeats AB AC BA BC CA CB n! / (n − k)!
combinations(it, k) unordered subsets, no repeats AB AC BC n! / (k! (n − k)!)
combinations_with_replacement(it, k) unordered, with repeats AA AB AC BB BC CC (n + k − 1)! / (k! (n − 1)!)
import operator
from itertools import (accumulate, batched, chain, combinations, compress, count,
cycle, groupby, islice, pairwise, permutations, product,
starmap, takewhile, zip_longest)
print(list(islice(count(10, 5), 3)), list(islice(cycle("ab"), 5)))
print(list(accumulate([3, 1, 4, 1, 5])), list(accumulate([3, 1, 4, 1, 5], max)))
print(list(accumulate([1, 2, 3, 4], operator.mul, initial=10)))
print(list(batched(range(7), 3)), list(pairwise("abcd")))
print(list(chain("ab", [1, 2])), list(chain.from_iterable([[1], [2, 3]])))
print(list(compress("abcd", [1, 0, 1, 0])), list(takewhile(lambda x: x < 5, [1, 4, 6])))
print(list(starmap(pow, [(2, 3), (3, 2)])), list(zip_longest("ab", "x", fillvalue="-")))
print(["".join(p) for p in product("AB", repeat=2)], len(list(permutations("ABCD", 2))))
print(["".join(c) for c in combinations("ABCD", 2)])
Output
[10, 15, 20] ['a', 'b', 'a', 'b', 'a']
[3, 4, 8, 9, 14] [3, 3, 4, 4, 5]
[10, 10, 20, 60, 240]
[(0, 1, 2), (3, 4, 5), (6,)] [('a', 'b'), ('b', 'c'), ('c', 'd')]
['a', 'b', 1, 2] [1, 2, 3]
['a', 'c'] [1, 4]
[8, 9] [('a', 'x'), ('b', '-')]
['AA', 'AB', 'BA', 'BB'] 12
['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
from itertools import groupby
from operator import itemgetter
sales = [("North", 120), ("South", 80), ("North", 50), ("South", 30), ("East", 10)]
unsorted = [(region, len(list(g))) for region, g in groupby(sales, key=itemgetter(0))]
print(unsorted) # runs of equal keys only
by_region = sorted(sales, key=itemgetter(0)) # sort by the same key first
for region, group in groupby(by_region, key=itemgetter(0)):
print(region, sum(amount for _, amount in group))
print([(k, len(list(g))) for k, g in groupby("aaabccaa")]) # run-length encoding
Output
[('North', 1), ('South', 1), ('North', 1), ('South', 1), ('East', 1)]
East 10
North 170
South 110
[('a', 3), ('b', 1), ('c', 2), ('a', 2)]
from collections import deque
from itertools import chain, islice, repeat, filterfalse, tee, zip_longest
def take(n, iterable):
return list(islice(iterable, n))
def nth(iterable, n, default=None):
return next(islice(iterable, n, None), default)
def first_true(iterable, default=None, pred=None):
return next(filter(pred, iterable), default)
def sliding_window(iterable, n):
it = iter(iterable)
window = deque(islice(it, n - 1), maxlen=n)
for x in it:
window.append(x)
yield tuple(window)
def unique_everseen(iterable, key=None):
seen = set()
for element in iterable:
k = element if key is None else key(element)
if k not in seen:
seen.add(k)
yield element
def partition(pred, iterable):
t1, t2 = tee(iterable)
return list(filterfalse(pred, t1)), list(filter(pred, t2))
def roundrobin(*iterables):
sentinel = object()
for group in zip_longest(*iterables, fillvalue=sentinel):
yield from (x for x in group if x is not sentinel)
def padnone(iterable):
return chain(iterable, repeat(None))
print(take(3, "abcdef"), nth("abcdef", 2), first_true([0, "", 7, 8]))
print(list(sliding_window([1, 2, 3, 4, 5], 3)))
print(list(unique_everseen("AaBbCcA", key=str.lower)), partition(str.isdigit, "a1b2"))
print(list(roundrobin("ABC", "D", "EF")), take(4, padnone([1, 2])))
Output
['a', 'b', 'c'] c 7
[(1, 2, 3), (2, 3, 4), (3, 4, 5)]
['A', 'B', 'C'] (['a', 'b'], ['1', '2'])
['A', 'D', 'E', 'B', 'F', 'C'] [1, 2, None, None]
Recipe Does Also in
take(n, it) first n items as a list more_itertools.take
nth(it, n) item n or a default
first_true(it, default, pred) first truthy (or matching) item
sliding_window(it, n) overlapping windows of size n more_itertools.windowed
unique_everseen(it, key) dedupe, keep order, works on streams
partition(pred, it) split into false and true items
roundrobin(*its) interleave iterables
batched(it, n) chunks built in since 3.12; strict=True in 3.13
flatten(list_of_lists) one level chain.from_iterable

Each stage takes an iterator and yields items. Nothing runs until the last stage pulls values, and memory stays constant whatever the file size.

from collections import Counter
from collections.abc import Iterable, Iterator
type Record = dict[str, str] # type alias statement (3.12+)
def read_lines(path: str) -> Iterator[str]:
with open(path, encoding="utf-8") as f:
for line in f:
yield line.rstrip("\n")
def parse(lines: Iterable[str]) -> Iterator[Record]:
for line in lines:
parts = line.split(maxsplit=4)
if len(parts) == 5 and parts[2] in {"INFO", "WARNING", "ERROR", "DEBUG"}:
yield {"level": parts[2], "source": parts[3], "message": parts[4]}
def only(records: Iterable[Record], *levels: str) -> Iterator[Record]:
return (r for r in records if r["level"] in levels)
problems = only(parse(read_lines("data/logs/app.log")), "WARNING", "ERROR")
print(Counter(r["level"] for r in problems))
first_error = next(only(parse(read_lines("data/logs/app.log")), "ERROR"), None)
print(first_error["source"], first_error["message"][:60])
Output
Counter({'WARNING': 25, 'ERROR': 7})
[db] OperationalError: database is locked (attempt 1/3), retrying
import csv
from itertools import batched, islice
def revenue_rows(path):
with open(path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
yield row["category"], float(row["revenue"])
totals = {}
for batch in batched(revenue_rows("data/sales.csv"), 5000): # 5,000 rows at a time
for category, revenue in batch:
totals[category] = totals.get(category, 0) + revenue
for category, total in sorted(totals.items()):
print(f"{category:<12}{total:>14,.2f}")
print(list(islice(revenue_rows("data/sales.csv"), 2)))
Output
Beauty 150,417.76
Books 106,908.12
Clothing 314,686.62
Electronics 1,808,108.17
Home 672,294.61
Sports 544,108.55
[('Home', 66.49), ('Clothing', 14.99)]
Stage Pattern
source with open(...) inside a generator; yields lines or rows
transform generator function or expression: parse, clean, enrich
filter (r for r in rows if ...), filter, takewhile, dropwhile
limit islice(rows, n) while you develop
group batched for chunks; groupby on sorted input
sink sum, Counter, max, a for loop that writes, csv.writer.writerows
Hint Use
Iterable[T] parameters: anything you can loop over
Iterator[T] return type of most generator functions
Generator[Y, S, R] when you use send or the return value; Generator[int, None, None] (Generator[int] on 3.13+)
AsyncIterator[T] async def with yield
import from collections.abc (not typing)
Trap Symptom Fix
iterating an iterator twice the second loop is empty make a list, or call the generator function again
x in iterator consumes items up to the match use a list or set for membership
len(gen) TypeError: object of type 'generator' has no len() sum(1 for _ in gen) or a list
gen[0] TypeError: 'generator' object is not subscriptable next(gen) or islice
printing a generator <generator object ...> list(gen) for small ones
groupby on unsorted data the same key appears in several groups sorted(data, key=k) first
keeping a groupby group for later it is empty after the next group list(group) at once
tee then using the original the tees miss items use only the tees
tee with one copy far ahead memory grows use a list
raise StopIteration in a generator RuntimeError: generator raised StopIteration return
next(gen) on an empty generator StopIteration escapes next(gen, default)
a generator over an open file returned from with ValueError: I/O operation on closed file open the file inside the generator
a generator expression’s first for evaluated at once; the rest are lazy build it where the data is ready
zip(it, it) pairs consecutive items (a trick, not a bug) use batched(it, 2) for clarity
zip on unequal lengths silent truncation zip(..., strict=True) or zip_longest
map with a lambda per item slower and less readable a generator expression
side effects in a generator they run only when consumed, maybe never consume with a loop, or do the work eagerly

Copy-ready templates for decorators and context managers, how they stack, the functools helpers that go with them, and the contextlib toolbox (suppress, ExitStack, redirect_stdout, closing, nullcontext, chdir). Every runnable block is checked against its output.

I want to… Use… Example
run code before and after every call a decorator @log_calls
keep the wrapped function’s name and docstring @functools.wraps(func) on the inner wrapper
pass settings to a decorator a decorator factory (3 levels) @retry(times=3)
allow @deco and @deco(n=2) def deco(func=None, *, n=1): see optional arguments
keep state between calls a class with __call__, or a function attribute @CountCalls
keep the type checker happy ParamSpec: def deco[**P, R](func: Callable[P, R]) -> Callable[P, R] see typed decorators
reach the undecorated function f.__wrapped__ tests, debugging
cache results of a pure function @functools.cache unbounded
cache with a size limit @functools.lru_cache(maxsize=256) f.cache_info(), f.cache_clear()
compute an attribute once per instance @functools.cached_property lazy, then stored
choose an implementation by argument type @functools.singledispatch @fmt.register
register functions in a dict a registry decorator @command("load")
change a class after it is defined a class decorator @dataclass, @register
clean up whatever happens with and a context manager with open(p) as f:
write a context manager quickly @contextlib.contextmanager yield inside try / finally
write a reusable or stateful manager a class with __enter__ / __exit__
ignore one exception type contextlib.suppress(E) with suppress(FileNotFoundError):
open a dynamic number of resources contextlib.ExitStack stack.enter_context(open(p))
register clean-up callbacks stack.callback(func, *args)
capture print output contextlib.redirect_stdout(buffer)
call close() on exit contextlib.closing(obj) old APIs without with
make a manager optional contextlib.nullcontext() lock if threaded else nullcontext()
change the working folder temporarily contextlib.chdir(path) (3.11+)
use a manager as a decorator too contextlib.ContextDecorator @timer() and with timer():
open several managers in one statement parenthesized with (3.10+) with (open(a) as f, open(b) as g):
temporarily change a setting a manager that restores in finally decimal.localcontext(), np.errstate
silence a known warning in one block warnings.catch_warnings() see errors
@decorator
def f(): ...
# is exactly:
def f(): ...
f = decorator(f)
@a
@b
def g(): ...
# is g = a(b(g)): b wraps first, a is the outer layer and runs first
import functools
def log_calls(func):
@functools.wraps(func) # copy __name__, __doc__, __wrapped__
def wrapper(*args, **kwargs):
print(f"-> {func.__name__}{args} {kwargs}")
result = func(*args, **kwargs)
print(f"<- {func.__name__} returned {result!r}")
return result
return wrapper
@log_calls
def add(a, b=0):
"""Add two numbers."""
return a + b
add(2, b=3)
print(add.__name__, add.__doc__, add.__wrapped__(1, 1))
Output
-> add(2,) {'b': 3}
<- add returned 5
add Add two numbers. 2
import functools
def retry(times=3, exceptions=(Exception,)):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except exceptions as exc:
print(f"attempt {attempt} failed: {exc}")
if attempt == times:
raise
return wrapper
return decorator
calls = {"n": 0}
@retry(times=3, exceptions=(ConnectionError,))
def fetch():
calls["n"] += 1
if calls["n"] < 3:
raise ConnectionError("timeout")
return "data"
print(fetch())
Output
attempt 1 failed: timeout
attempt 2 failed: timeout
data
import functools
def tag(func=None, *, label="INFO"):
if func is None: # called as @tag(label=...)
return functools.partial(tag, label=label)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return f"[{label}] {func(*args, **kwargs)}"
return wrapper
@tag
def hello():
return "hello"
@tag(label="WARN")
def disk():
return "disk 91% full"
print(hello(), disk())
Output
[INFO] hello [WARN] disk 91% full
import functools
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func) # the class version of @wraps
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
return self.func(*args, **kwargs)
@CountCalls
def square(x):
return x * x
print([square(n) for n in range(4)], square.calls, square.__name__)
Output
[0, 1, 4, 9] 4 square

A class-based decorator on a method loses self binding, because the instance is not a descriptor. Use a function decorator for methods, or add __get__.

import functools
import time
from collections.abc import Callable
def timed[**P, R](func: Callable[P, R]) -> Callable[P, R]: # 3.12+ syntax
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
elapsed = time.perf_counter() - start
print(f"{func.__name__} took less than 1 s: {elapsed < 1}")
return wrapper
@timed
def total(values: list[float], *, scale: float = 1.0) -> float:
return sum(values) * scale
print(total([1.5, 2.5], scale=2))
Output
total took less than 1 s: True
8.0
Case Signature
keep parameters and return type def deco[**P, R](func: Callable[P, R]) -> Callable[P, R]
factory with settings def deco[**P, R](n: int) -> Callable[[Callable[P, R]], Callable[P, R]]
changes the return type def deco[**P, R](func: Callable[P, R]) -> Callable[P, R | None]
adds a first argument Callable[Concatenate[Session, P], R] → Callable[P, R]
wrapper parameters def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
before 3.12 P = ParamSpec("P"), R = TypeVar("R") from typing
avoid Callable[..., Any]: the checker loses the signature
Python 3.10 and 3.11
from typing import Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def timed(func: Callable[P, R]) -> Callable[P, R]: ...
from collections.abc import Callable
COMMANDS: dict[str, Callable[..., str]] = {}
def command(name):
def register(func):
COMMANDS[name] = func # register, return the function unchanged
return func
return register
@command("greet")
def greet(who):
return f"hello {who}"
@command("shout")
def shout(who):
return f"HELLO {who.upper()}"
def add_repr(cls): # a class decorator gets and returns the class
def __repr__(self):
fields = ", ".join(f"{k}={v!r}" for k, v in vars(self).items())
return f"{cls.__name__}({fields})"
cls.__repr__ = __repr__
return cls
@add_repr
class Store:
def __init__(self, store_id, city):
self.store_id, self.city = store_id, city
print(sorted(COMMANDS), COMMANDS["shout"]("ana"), Store("S01", "Chicago"))
Output
['greet', 'shout'] HELLO ANA Store(store_id='S01', city='Chicago')
def deco(name):
def decorator(func):
def wrapper():
print(f"{name} before")
func()
print(f"{name} after")
return wrapper
return decorator
@deco("outer") # applied last, runs first
@deco("inner") # applied first, closest to the function
def work():
print("work")
work()
Output
outer before
inner before
work
inner after
outer after
Stack Typical order (top to bottom)
web route + auth @app.get(...), then @login_required
method decorators @classmethod / @staticmethod / @property on top
caching + logging @log_calls above @cache logs every call; below it logs only cache misses
@pytest.mark... any order; marks only add metadata
Helper Does Note
wraps(func) copies __module__, __name__, __qualname__, __doc__, __annotations__, __type_params__; updates __dict__; sets __wrapped__ always use it in wrappers
update_wrapper(wrapper, func) the function form of wraps class-based decorators
cache unbounded memoization (3.9+) arguments must be hashable
lru_cache(maxsize=128) memoization with least-recently-used eviction maxsize=None is cache
lru_cache(typed=True) caches 1 and 1.0 separately
f.cache_info(), f.cache_clear() statistics, reset
cached_property computes once per instance, then stores in __dict__ not thread-safe; needs __dict__
singledispatch dispatch on the first argument’s type singledispatchmethod for methods
partial(f, *a, **kw) fix some arguments functions page
total_ordering fill in <=, >, >= from __eq__ and __lt__ class decorator
from functools import cache, cached_property, lru_cache, singledispatch
@lru_cache(maxsize=2)
def slow_square(n):
print(f"computing {n}")
return n * n
print([slow_square(n) for n in (2, 2, 3, 4, 2)])
print(slow_square.cache_info())
@cache
def ways(n): # number of ways to climb n stairs with steps of 1 or 2
return 1 if n < 2 else ways(n - 1) + ways(n - 2)
class Report:
def __init__(self, values):
self.values = values
@cached_property
def total(self):
print("summing")
return sum(self.values)
@singledispatch
def fmt(value):
return str(value)
@fmt.register
def _(value: float):
return f"{value:,.2f}"
@fmt.register
def _(value: list):
return " | ".join(fmt(v) for v in value)
r = Report([1, 2, 3])
print(ways(50), r.total, r.total, fmt([1234.5, 7, "x"]))
Output
computing 2
computing 3
computing 4
computing 2
[4, 4, 9, 16, 4]
CacheInfo(hits=1, misses=4, maxsize=2, currsize=2)
summing
20365011074 6 6 1,234.50 | 7 | x
Step Call Detail
enter value = manager.__enter__() value is bound by as
body your block
exit, no error manager.__exit__(None, None, None)
exit, with an error manager.__exit__(exc_type, exc, traceback) return True to suppress the error
with A() as a, B() as b: enters A then B; exits B then A like nested with

The other call and context-manager dunders are in the dunder methods page.

class Transaction:
"""Apply changes to a list; roll them back if the block fails."""
def __init__(self, data):
self.data = data
def __enter__(self):
self.snapshot = list(self.data)
return self.data # bound by `as`
def __exit__(self, exc_type, exc, tb):
if exc_type is not None:
self.data[:] = self.snapshot # roll back
print(f"rolled back after {exc_type.__name__}: {exc}")
return exc_type is ValueError # True suppresses the exception
stock = [5, 3]
with Transaction(stock) as items:
items.append(10)
with Transaction(stock) as items:
items.append(-1)
raise ValueError("negative stock")
print(stock)
Output
rolled back after ValueError: negative stock
[5, 3, 10]
from contextlib import contextmanager
@contextmanager
def section(title):
print(f"== {title} ==") # __enter__ part
try:
yield title.upper() # the value bound by `as`; the block runs here
except KeyError as exc: # handle (and suppress) chosen errors
print("missing key:", exc)
finally:
print(f"== end {title} ==") # always runs: clean-up
with section("load") as name:
print("working in", name)
with section("lookup"):
print({}["store"])
Output
== load ==
working in LOAD
== end load ==
== lookup ==
missing key: 'store'
== end lookup ==
Rule Detail
yield exactly once a second yield raises RuntimeError
put yield in try / finally otherwise clean-up is skipped when the block raises
re-raise by default an exception you do not catch propagates; one you catch is suppressed
it is also a decorator @section("x") on a function wraps each call
Tool Does Example
contextmanager build a manager from a generator above
asynccontextmanager the same for async with async database sessions
suppress(*errors) swallow the listed exceptions with suppress(FileNotFoundError): os.remove(p)
ExitStack() manage a dynamic number of managers files = [stack.enter_context(open(p)) for p in paths]
stack.callback(f, *args) call f at exit (LIFO)
stack.pop_all() move clean-ups to a new stack keep resources open on success
redirect_stdout(f), redirect_stderr(f) send print / errors to f capture library output
closing(obj) call obj.close() at exit with closing(urlopen(url)) as page:
aclosing(obj) call await obj.aclose() async generators
nullcontext(value) do nothing; as gets value optional managers
chdir(path) change the working directory, then restore it (3.11+) not thread-safe
ContextDecorator base class: usable as with and as @
AbstractContextManager base class; default __enter__ returns self
import io
from contextlib import ExitStack, chdir, closing, nullcontext, redirect_stdout, suppress
from pathlib import Path
from tempfile import TemporaryDirectory
buffer = io.StringIO()
with redirect_stdout(buffer):
print("captured line")
print(repr(buffer.getvalue()))
with suppress(FileNotFoundError):
Path("missing.txt").unlink() # no error if the file is missing
print("still running")
paths = ["a.txt", "b.txt"]
with ExitStack() as stack:
files = [stack.enter_context(open(p, "w", encoding="utf-8")) for p in paths]
stack.callback(print, "callback runs first (LIFO), then the files close")
for f in files:
f.write("x")
print([f.closed for f in files], [Path(p).read_text() for p in paths])
class Resource:
def close(self):
print("Resource.close() called")
with closing(Resource()):
pass
lock = None # e.g. threading.Lock() when running in threads
with lock or nullcontext():
print("no lock needed")
with TemporaryDirectory() as tmp, chdir(tmp):
Path("inside.txt").write_text("hi", encoding="utf-8")
print("inside:", sorted(p.name for p in Path().iterdir()))
print("back:", Path("inside.txt").exists())
Output
'captured line\n'
still running
callback runs first (LIFO), then the files close
[True, True] ['x', 'x']
Resource.close() called
no lock needed
inside: ['inside.txt']
back: False
from contextlib import ContextDecorator
class announce(ContextDecorator):
def __init__(self, label):
self.label = label
def __enter__(self):
print(f"start {self.label}")
return self
def __exit__(self, *exc):
print(f"stop {self.label}")
return False # do not suppress errors
@announce("job") # as a decorator
def job():
print("working")
job()
with announce("block"): # as a context manager
print("inline")
Output
start job
working
stop job
start block
inline
stop block
Manager Guarantees
open(path) the file is closed
tempfile.TemporaryDirectory() / NamedTemporaryFile() the folder or file is deleted
threading.Lock() the lock is released
sqlite3.connect(db) commit on success, rollback on error (it does not close; wrap in closing)
decimal.localcontext() precision and rounding restored
warnings.catch_warnings() warning filters restored
unittest.mock.patch(...) the original object restored
pytest.raises(E) the block must raise E
np.errstate(divide="ignore") NumPy error settings restored
pd.option_context("display.max_rows", 5) pandas options restored
torch.no_grad() gradient tracking restored
zipfile.ZipFile, tarfile.open archive closed
concurrent.futures.ThreadPoolExecutor() workers shut down, waits for tasks
httpx.Client() / requests.Session() connections closed
Trap Symptom Fix
no @functools.wraps f.__name__ is wrapper; docs and help() are wrong always wrap the inner function
wrapper does not return the decorated function returns None return func(*args, **kwargs)
a sync wrapper on an async def the wrapper returns the coroutine at once: timing or retry code never sees the real work make the wrapper async def and await func(...); branch on inspect.iscoroutinefunction(func)
@retry without parentheses on a factory TypeError or a function that never runs @retry(), or support both forms
decorator runs at import time side effects (prints, registration) at import intended for registries; keep other work in the wrapper
wrong stacking order @staticmethod under another decorator fails or misbehaves put @classmethod, @staticmethod, @property on top
@cache on a method keeps every self alive (memory leak) cache a module function, or use cached_property
@cache with list or dict arguments TypeError: unhashable type: 'list' pass tuples or frozensets
@cache on impure functions stale results (time, files, random) cache only pure functions
a class-based decorator on a method self is not passed function decorator, or implement __get__
Callable[..., Any] in a typed decorator the checker loses parameter types ParamSpec
@contextmanager without try / finally clean-up skipped when the block raises wrap yield in try / finally
__exit__ returns a truthy value by accident exceptions vanish silently return None or False unless you mean to suppress
suppress(Exception) hides real bugs list the narrow exceptions you expect
with sqlite3.connect(db) as con: the connection stays open with closing(sqlite3.connect(db)) as con, con:
with open(a) as f, open(b) as g: over 88 chars hard to read parenthesized with (...) (3.10+)
chdir in threads or async code other code sees the changed folder pass paths instead
one @contextmanager object used in two with blocks AttributeError: '_GeneratorContextManager' object has no attribute 'args' call the function again for each with

Everything about things going wrong: the exception hierarchy, how to catch, raise, chain and group exceptions, how to read a traceback, how to drive pdb, how to set up logging, and how to work with warnings. Every runnable block is checked against its output.

I want to… Use… Example
handle one error type try / except E as exc: except ValueError as exc:
handle several types the same way a tuple except (KeyError, IndexError):
run code only if no error happened else: keeps the try block small
always run clean-up finally: or a with block close, unlock, delete temp files
signal a bad argument raise ValueError("...") wrong value, right type
signal a wrong type raise TypeError("...")
re-raise the current error bare raise inside except keeps the traceback
wrap a low-level error raise NewError(...) from exc the cause is kept
hide the original error raise NewError(...) from None cleaner messages for users
add context to an error exc.add_note("row 42") (3.11+) shown under the message
define my own error class AppError(Exception): one base class per package
raise several errors at once ExceptionGroup("msg", [e1, e2]) validation, concurrent tasks
handle parts of a group except* ValueError as eg: each matching sub-group
ignore an expected error contextlib.suppress(E) with suppress(FileNotFoundError):
get the traceback as text traceback.format_exc() in an except block
log an error with its traceback log.exception("msg") inside except
check an internal assumption assert cond, "msg" not for user input; -O removes it
pause in the debugger breakpoint() then p x, n, s, c
debug after a crash python -m pdb -c continue script.py or pdb.pm() in the REPL
turn breakpoints off PYTHONBREAKPOINT=0 environment variable
print a variable with its name print(f"{x=}") x=42
start logging in a script logging.basicConfig(level=logging.INFO) once, at startup
get a logger in a module log = logging.getLogger(__name__)
log with lazy arguments log.info("loaded %d rows", n) not an f-string
send logs to a file logging.FileHandler(path) or basicConfig(filename=...)
warn about deprecated use warnings.warn("...", DeprecationWarning, stacklevel=2) points at the caller
turn warnings into errors python -W error script.py or warnings.simplefilter("error")
silence one known warning warnings.catch_warnings() + filterwarnings("ignore", ...) narrow: category and message
record warnings in a test warnings.catch_warnings(record=True) pytest.warns(...) in pytest
exit with a status code sys.exit(1) or raise SystemExit("message")
BaseException
├── SystemExit, KeyboardInterrupt, GeneratorExit (do not catch these by accident)
├── BaseExceptionGroup
│ └── ExceptionGroup (also an Exception)
└── Exception
├── ArithmeticError: ZeroDivisionError, OverflowError, FloatingPointError
├── LookupError: IndexError, KeyError
├── ValueError
│ └── UnicodeError: UnicodeDecodeError, UnicodeEncodeError
├── TypeError, AttributeError, AssertionError, EOFError, BufferError
├── NameError
│ └── UnboundLocalError
├── ImportError
│ └── ModuleNotFoundError
├── OSError (alias IOError)
│ ├── FileNotFoundError, FileExistsError, PermissionError
│ ├── IsADirectoryError, NotADirectoryError, TimeoutError
│ └── ConnectionError: ConnectionRefusedError, ConnectionResetError, BrokenPipeError
├── RuntimeError: RecursionError, NotImplementedError, PythonFinalizationError (3.13)
├── StopIteration, StopAsyncIteration
├── SyntaxError
│ └── IndentationError: TabError
├── MemoryError, ReferenceError, SystemError
└── Warning: UserWarning, DeprecationWarning, FutureWarning, RuntimeWarning, ...
Exception Typical cause Example message
ValueError right type, bad value invalid literal for int() with base 10: 'abc'
TypeError wrong type or wrong number of arguments unsupported operand type(s) for +: 'int' and 'str'
KeyError missing dict key 'store_id'
IndexError index past the end list index out of range
AttributeError missing attribute or method; often None 'NoneType' object has no attribute 'strip'
NameError typo or not defined yet name 'totl' is not defined (3.10+ adds “Did you mean” hints)
UnboundLocalError assignment makes the name local cannot access local variable 'x' where it is not associated with a value
ZeroDivisionError /, // or % by 0 division by zero
FileNotFoundError wrong path or working folder [Errno 2] No such file or directory: 'data.csv'
PermissionError no rights, or file open in another program [Errno 13] Permission denied: ...
UnicodeDecodeError the file is not in the given encoding 'utf-8' codec can't decode byte 0xe9 ...
ModuleNotFoundError package not installed in this environment No module named 'pandas'
RecursionError no base case maximum recursion depth exceeded
StopIteration next() on an exhausted iterator
AssertionError an assert failed the assert message
NotImplementedError abstract method or unfinished branch
json.JSONDecodeError invalid JSON (a ValueError) Expecting value: line 1 column 1 (char 0)
csv.Error, sqlite3.Error, httpx.HTTPError library errors catch the library’s base class
for exc_type in (FileNotFoundError, KeyError, UnicodeDecodeError, ModuleNotFoundError):
print(" -> ".join(c.__name__ for c in exc_type.__mro__[:-2]))
print(issubclass(KeyboardInterrupt, Exception), issubclass(OSError, Exception))
Output
FileNotFoundError -> OSError -> Exception
KeyError -> LookupError -> Exception
UnicodeDecodeError -> UnicodeError -> ValueError -> Exception
ModuleNotFoundError -> ImportError -> Exception
False True
def safe_ratio(a, b):
try:
result = a / b # only the code that can fail
except ZeroDivisionError:
print(" except: b is 0")
return None
except TypeError as exc:
print(" except:", exc)
return None
else:
print(" else: no error") # runs only when try succeeded
return round(result, 2)
finally:
print(" finally: always") # runs even after return
for args in [(1, 3), (1, 0), (1, "x")]:
print(args, "->", safe_ratio(*args))
Output
else: no error
finally: always
(1, 3) -> 0.33
except: b is 0
finally: always
(1, 0) -> None
except: unsupported operand type(s) for /: 'int' and 'str'
finally: always
(1, 'x') -> None
Clause Runs when Use
try first only the line(s) that can fail
except E E or a subclass was raised the first matching clause wins; order from specific to general
except E as exc as above; exc is deleted after the block read exc.args, str(exc)
else try finished with no exception code that depends on success but must not be guarded
finally always: after success, error, return, break clean-up; never return from here
bare except: anything, even KeyboardInterrupt avoid; use except Exception: at the top level only
def parse_price(text):
try:
return float(text.removeprefix("$"))
except ValueError as exc:
raise ValueError(f"bad price {text!r}") from exc # explicit cause
try:
parse_price("N/A")
except ValueError as exc:
print(exc, "| cause:", repr(exc.__cause__))
try:
try:
store = {}["store"]
except KeyError:
raise LookupError("store not configured") from None # hide the KeyError
except LookupError as exc:
print(exc, exc.__cause__, exc.__suppress_context__)
try:
int("x")
except ValueError as exc:
exc.add_note("while reading row 42 of data/sales.csv") # 3.11+
print(exc.__notes__)
Output
bad price 'N/A' | cause: ValueError("could not convert string to float: 'N/A'")
store not configured None True
['while reading row 42 of data/sales.csv']
Form Traceback shows Use
raise the original error and traceback log, then re-raise
raise New(...) inside except both, “During handling of the above exception, another exception occurred” usually a bug in the handler
raise New(...) from exc both, “The above exception was the direct cause of the following exception” translate low-level errors
raise New(...) from None only the new error user-facing messages
exc.add_note(text) the note under the message add the row, file or id
raise ValueError (a class) same as ValueError() prefer a message
class PipelineError(Exception):
"""Base class: callers can catch every error of this package."""
class ValidationError(PipelineError):
def __init__(self, column, value, reason):
super().__init__(f"{column}={value!r}: {reason}") # sets str(exc)
self.column, self.value, self.reason = column, value, reason
class MissingFileError(PipelineError, FileNotFoundError):
"""Also a FileNotFoundError, so generic handlers still work."""
try:
raise ValidationError("quantity", -3, "must be >= 0")
except PipelineError as exc:
print(type(exc).__name__, exc, exc.column)
print(issubclass(MissingFileError, OSError))
Output
ValidationError quantity=-3: must be >= 0 quantity
True
Rule Detail
inherit from Exception never from BaseException
name ends with Error ConfigError, ValidationError
one base per package callers write except mypackage.Error:
call super().__init__(message) so str(exc) and pickling work
store data as attributes handlers should not parse the message
also subclass a built-in when it fits class NotFound(MyError, KeyError)
def validate(row):
errors = []
if not row["id"].startswith("O"):
errors.append(ValueError(f"bad id {row['id']!r}"))
if row["qty"] < 0:
errors.append(ValueError(f"negative qty {row['qty']}"))
if "price" not in row:
errors.append(KeyError("price"))
if errors:
raise ExceptionGroup("row invalid", errors)
try:
validate({"id": "X1", "qty": -2})
except* ValueError as group: # every ValueError of the group
print("values:", [str(e) for e in group.exceptions])
except* KeyError as group: # the KeyErrors; both clauses can run
print("keys:", [str(e) for e in group.exceptions])
Output
values: ["bad id 'X1'", 'negative qty -2']
keys: ["'price'"]
Fact Detail
ExceptionGroup(msg, [excs]) holds Exception subclasses; BaseExceptionGroup for others
except* T gets a sub-group with the matching exceptions; several clauses can run
unmatched exceptions re-raised in a new group after the except* clauses
plain except ExceptionGroup catches the whole group
eg.subgroup(pred), eg.split(T) filter a group by hand
where they come from asyncio.TaskGroup, trio, your own validation
no mixing one try uses except or except*, not both

load_prices.py:

load_prices.py
def parse_price(text):
return float(text.removeprefix("$"))
def load(rows):
return [parse_price(row["price"]) for row in rows]
def main():
rows = [{"price": "$4.99"}, {"price": "N/A"}]
try:
prices = load(rows)
except ValueError as exc:
raise RuntimeError("cannot load prices") from exc
print(sum(prices))
main()

What Python 3.13 prints (your folder appears in place of /path/to/my-course):

Traceback (most recent call last):
File "/path/to/my-course/load_prices.py", line 12, in main
prices = load(rows)
File "/path/to/my-course/load_prices.py", line 6, in load
return [parse_price(row["price"]) for row in rows]
~~~~~~~~~~~^^^^^^^^^^^^^^
File "/path/to/my-course/load_prices.py", line 2, in parse_price
return float(text.removeprefix("$"))
ValueError: could not convert string to float: 'N/A'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/path/to/my-course/load_prices.py", line 18, in <module>
main()
~~~~^^
File "/path/to/my-course/load_prices.py", line 14, in main
raise RuntimeError("cannot load prices") from exc
RuntimeError: cannot load prices
Step Look at Question
1 the very last line what went wrong: type and message
2 the last frame of your code where it was raised (skip library frames)
3 frames above it, bottom to top how the program got there; where the bad value came from
4 ~~~^^^ markers (3.11+) which part of the line ran
5 “direct cause” a chained error (from exc): the first block is the root cause
6 “During handling of the above exception” a second error inside an except block
7 +-+--- boxes an exception group: one box per sub-exception

The traceback module gives the same data as values:

import traceback
def parse_price(text):
return float(text.removeprefix("$"))
try:
prices = [parse_price(t) for t in ["$4.99", "N/A"]]
except ValueError as exc:
for frame in traceback.extract_tb(exc.__traceback__):
print(f"{frame.name:<12} line {frame.lineno}: {frame.line}")
print(traceback.format_exception_only(exc)[-1], end="")
Output
<module> line 9: prices = [parse_price(t) for t in ["$4.99", "N/A"]]
parse_price line 5: return float(text.removeprefix("$"))
ValueError: could not convert string to float: 'N/A'
Command Does
h / h cmd help
p expr / pp expr print / pretty-print a value
n next line (step over calls)
s step into a call
r continue until the current function returns
c continue to the next breakpoint
unt N continue until line N (leaves loops)
j N jump to line N (in the current function)
l / ll list source around the current line / the whole function
w where: the call stack
u / d move up to the caller / down again
b N, b file.py:N, b func set a breakpoint
b N, cond conditional breakpoint: b 24, total < 0
tbreak N one-time breakpoint
cl N / disable N / enable N clear / disable / enable breakpoint N
a arguments of the current function
display expr show expr whenever it changes
!stmt run a Python statement (!n = 3 when n is a variable)
interact a full REPL in the current frame
q quit
Terminal
python -m pdb script.py # start paused at the first line
python -m pdb -c continue script.py # run; pause where it crashes (post-mortem)
PYTHONBREAKPOINT=0 python script.py # ignore every breakpoint() call
python -X dev script.py # dev mode: more warnings and checks
python -i script.py # REPL after a crash; then: import pdb; pdb.pm()
Technique When
print(f"{x=}"), print(repr(x), type(x)) quick checks; hidden spaces and types
breakpoint() pause at a line and look around
editor debugger (VS Code, PyCharm) breakpoints, watches, the same pdb ideas with a UI
assert invariants catch a bad state early, near the cause
smallest failing input 3 rows, not 20,000
logging at DEBUG long-running or unattended programs
a test that reproduces the bug fix it once, keep it fixed
%debug in Jupyter post-mortem after a failed cell
Level Value Use
DEBUG 10 detail for developers
INFO 20 normal progress
WARNING 30 something odd, handled; the default threshold
ERROR 40 an operation failed
CRITICAL 50 the program cannot continue
import logging
logging.basicConfig(
level=logging.INFO, # show INFO and above
format="%(levelname)-8s %(name)s: %(message)s", # add %(asctime)s in real apps
force=True, # replace any earlier configuration
)
log = logging.getLogger("sales.loader") # in modules: logging.getLogger(__name__)
log.debug("not shown: below the level")
log.info("loaded %d rows from %s", 20228, "data/sales.csv") # lazy formatting
log.warning("%d rows without customer_id", 23)
try:
ratio = 1 / 0
except ZeroDivisionError as exc:
log.error("ratio failed: %s", exc) # log.exception() also prints the traceback
logging.getLogger("sales").setLevel(logging.ERROR) # quiet a whole logger tree
log.warning("not shown: the parent logger is at ERROR")
Output
INFO sales.loader: loaded 20228 rows from data/sales.csv
WARNING sales.loader: 23 rows without customer_id
ERROR sales.loader: ratio failed: division by zero
Piece Job Example
logger named source with a level; names form a tree (a.b is a child of a) logging.getLogger(__name__)
handler sends records somewhere; has its own level StreamHandler(), FileHandler(path), RotatingFileHandler(path, maxBytes=..., backupCount=3)
formatter the line layout Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")
filter drop or edit records handler.addFilter(func)
propagate pass records up to parent handlers False to avoid double lines
NullHandler libraries add it so they stay silent until the app configures logging logging.getLogger(__name__).addHandler(logging.NullHandler())
Format field Shows
%(asctime)s the time (datefmt="%Y-%m-%d %H:%M:%S" to change it)
%(levelname)s, %(levelname)-8s the level, padded
%(name)s the logger name
%(message)s the message with arguments
%(module)s, %(funcName)s, %(lineno)d where the call is
%(process)d, %(threadName)s process and thread
logging_config.py
import logging.config
logging.config.dictConfig({
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"plain": {"format": "%(asctime)s %(levelname)-8s %(name)s: %(message)s"},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "INFO",
"formatter": "plain",
},
"file": {
"class": "logging.handlers.RotatingFileHandler",
"filename": "output/app.log",
"maxBytes": 1_000_000,
"backupCount": 3,
"formatter": "plain",
"encoding": "utf-8",
},
},
"root": {"level": "DEBUG", "handlers": ["console", "file"]},
})
Category Shown by default Use
UserWarning yes the default for warnings.warn
DeprecationWarning only in __main__ and tests for other developers: an API will go away
FutureWarning yes for end users: behavior will change (pandas uses it)
PendingDeprecationWarning no a future deprecation
RuntimeWarning yes dubious run-time behavior (NumPy overflow, never-awaited coroutines)
SyntaxWarning yes dubious syntax: "\d" invalid escape (3.12+)
ResourceWarning no (shown with -X dev) unclosed files and sockets
Action (filterwarnings, -W) Effect
"default" show once per location
"error" raise the warning as an exception
"ignore" never show
"always" show every time
"once" show only the first time
import warnings
def old_api():
message = "old_api() is deprecated; use new_api()"
warnings.warn(message, DeprecationWarning, stacklevel=2) # point at the caller
return 42
with warnings.catch_warnings(record=True) as caught: # filters restored afterward
warnings.simplefilter("always")
old_api()
print(len(caught), caught[0].category.__name__, caught[0].message)
with warnings.catch_warnings():
warnings.simplefilter("error") # warnings become exceptions in this block
try:
old_api()
except DeprecationWarning as exc:
print("raised:", exc)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="old_api", category=DeprecationWarning)
print(old_api()) # silenced: narrow by message and category
Output
1 DeprecationWarning old_api() is deprecated; use new_api()
raised: old_api() is deprecated; use new_api()
42
Terminal
python -W error script.py # every warning is an error
python -W "ignore::DeprecationWarning" script.py # action:message:category:module:line
PYTHONWARNINGS=default python script.py # the same through the environment
pytest -W error::FutureWarning # fail tests on FutureWarning
Trap Symptom Fix
bare except: or except Exception: pass bugs and Ctrl+C vanish catch the narrow type; log what you swallow
a big try block the handler catches errors from the wrong line keep only the failing call in try; use else
except (A, B) written as except A, B SyntaxError parentheses are required
general except before specific ones the specific clause never runs order from specific to general
raise New(...) inside except without from confusing “During handling…” traceback from exc or from None
return in finally swallows the exception (SyntaxWarning in 3.14) never return or break in finally
exc used after the except block NameError: it is deleted copy it: error = exc
catching StopIteration or KeyboardInterrupt by accident loops end or Ctrl+C is ignored catch Exception subclasses only
assert for input validation skipped with python -O if not ok: raise ValueError(...)
assert (x, "msg") always passes: a non-empty tuple assert x, "msg"
log.info(f"... {x}") formats even when INFO is off log.info("... %s", x)
logging.basicConfig called twice the second call does nothing call once at startup, or pass force=True
print for errors goes to stdout, no level or time logging, or print(..., file=sys.stderr)
duplicate log lines a handler on the logger and on the root log.propagate = False, or handlers only on the root
library code calls basicConfig overrides the app’s setup libraries only getLogger(__name__) + NullHandler
warnings.filterwarnings("ignore") globally hides real problems narrow by category, message and module, inside catch_warnings()
warnings.warn without stacklevel=2 the warning points at your library line stacklevel=2 points at the caller
exception messages differ by version hints and wording change between 3.12 and 3.13 match on the type, not the message text

Working with the file system and the common file formats: pathlib for paths, open() modes and encodings, csv, json, pickle, tomllib, shutil, tempfile and folder walking. The examples read the course datasets in data/ and write to output/. Every runnable block is checked against its output.

I want to… Use… Example
build a path Path and / Path("data") / "sales.csv"
get the file name, stem, extension .name, .stem, .suffix Path("a/b.csv").stem → 'b'
get the parent folder .parent Path("data/api/x.json").parent
change the extension .with_suffix(".parquet")
check that a file exists p.exists(), p.is_file(), p.is_dir()
create a folder and its parents p.mkdir(parents=True, exist_ok=True)
read a whole small text file p.read_text(encoding="utf-8")
write a whole text file p.write_text(text, encoding="utf-8") overwrites
read a file line by line with open(p, encoding="utf-8") as f: for line in f: constant memory
append to a file open(p, "a", encoding="utf-8")
create a file only if it does not exist open(p, "x") FileExistsError otherwise
read binary data p.read_bytes() or open(p, "rb") images, pickles, unknown encodings
list the files of a folder sorted(p.iterdir())
find files by pattern p.glob("*.csv"), p.rglob("*.json") rglob is recursive
walk a folder tree Path.walk() (3.12+) or os.walk()
file size, modification time p.stat().st_size, .st_mtime
delete a file p.unlink(missing_ok=True)
delete a folder tree shutil.rmtree(p) no undo
copy or move shutil.copy2(src, dst), shutil.move(src, dst) copytree for folders
rename, replacing the target p.replace(target) atomic on the same drive
read CSV rows as dicts csv.DictReader(f) open with newline=""
write CSV from dicts csv.DictWriter(f, fieldnames=...) writeheader(), writerows()
read JSON json.load(f) / json.loads(text)
write JSON readably json.dump(obj, f, indent=2, ensure_ascii=False)
serialize dates and other types to JSON default=str json.dumps(obj, default=str)
read and write JSON Lines one json.loads(line) per line logs, streams
read a TOML config tomllib.load(f) (binary mode) pyproject.toml
save any Python object (trusted use only) pickle.dump(obj, f) never load untrusted pickles
get a temporary folder tempfile.TemporaryDirectory() deleted after with
read a gzip file gzip.open(p, "rt", encoding="utf-8")
open a zip archive zipfile.ZipFile(p) .namelist(), .open(name)
make an archive of a folder shutil.make_archive("out", "zip", folder)
find a program on the PATH shutil.which("git") None if missing
get the script’s own folder Path(__file__).resolve().parent not the working folder
expand ~ Path("~/data").expanduser()
Attribute or method p = Path("data/api/products_page_1.json") Note
p.name 'products_page_1.json'
p.stem, p.suffix 'products_page_1', '.json'
p.suffixes ['.json'] ['.tar', '.gz'] for archives
p.parent, p.parents[1] data/api, data
p.parts ('data', 'api', 'products_page_1.json')
p.with_suffix(".csv") data/api/products_page_1.csv
p.with_name("x.json"), p.with_stem("x") data/api/x.json with_stem is 3.9+
p.is_absolute() False
p.resolve() absolute path, symlinks resolved
p.relative_to("data") api/products_page_1.json ValueError if not inside
p.is_relative_to("data") True
p.match("*.json"), p.full_match("data/**/*.json") True full_match is 3.13+
p.exists(), p.is_file(), p.is_dir()
p.stat().st_size size in bytes
p.read_text(), p.write_text(), p.read_bytes(), p.write_bytes() whole-file I/O pass encoding= for text
p.open(mode, encoding=) same as open(p, ...)
p.iterdir(), p.glob(pat), p.rglob(pat), p.walk() iterate a folder order is arbitrary: sort
p.mkdir(parents=True, exist_ok=True), p.touch() create
p.unlink(missing_ok=True), p.rmdir() delete a file / an empty folder
p.rename(t), p.replace(t) move or rename replace overwrites t
Path.cwd(), Path.home() working folder, home folder
Path("~").expanduser() expand ~
from pathlib import Path
p = Path("data") / "api" / "products_page_1.json"
print(p, p.name, p.stem, p.suffix, p.parent)
print(p.parts, p.parents[1], p.suffixes)
print(p.with_suffix(".csv"), p.with_stem("page1"), p.relative_to("data"))
print(p.exists(), p.is_file(), p.parent.is_dir(), p.stat().st_size > 0)
print(sorted(f.name for f in Path("data/reports").glob("*.csv"))[:3])
print(sorted(str(f) for f in Path("data").rglob("*.log")), p.as_posix())
Output
data/api/products_page_1.json products_page_1.json products_page_1 .json data/api
('data', 'api', 'products_page_1.json') data ['.json']
data/api/products_page_1.csv data/api/page1.json api/products_page_1.json
True True True True
['2024-01.csv', '2024-02.csv', '2024-03.csv']
['data/logs/app.log'] data/api/products_page_1.json
Legacy os.path pathlib
os.path.join(a, b) Path(a) / b
os.path.exists(p), isfile, isdir p.exists(), p.is_file(), p.is_dir()
os.path.basename(p) p.name
os.path.dirname(p) p.parent
os.path.splitext(p) (p.stem, p.suffix); p.with_suffix(".csv") to change it
os.path.getsize(p) p.stat().st_size
os.path.expanduser("~/x") Path("~/x").expanduser()
os.path.abspath(p) p.resolve() (also resolves symlinks)

Atomic write: write a temporary file in the same folder, then replace the target in one step. A crash never leaves a half-written file.

atomic write
tmp = target.with_name(target.name + ".tmp") # same folder, same file system
tmp.write_text(text, encoding="utf-8")
tmp.replace(target) # atomic rename; overwrites target
Mode Read Write Creates Truncates Position Missing file
"r" (default) yes start FileNotFoundError
"w" yes yes yes start created
"a" yes yes end created
"x" yes yes start created; FileExistsError if it exists
"r+" yes yes start FileNotFoundError
"w+" yes yes yes yes start created
"a+" yes yes yes end created
add "b" ("rb", "wb") bytes in and out no encoding
add "t" (default) str in and out pass encoding
open() argument Use
encoding="utf-8" always, for text; the default depends on the platform
encoding="utf-8-sig" CSV files from Excel (removes the BOM)
errors="replace" / "backslashreplace" read damaged text without crashing
newline="" always for the csv module, read and write
newline="\n" write Unix line endings on Windows too
buffering=1 line-buffered text output (logs)
File method Does
f.read(), f.read(n) the whole rest / n characters (or bytes)
f.readline() one line with its \n; "" at the end of file
f.readlines() all lines as a list (loads everything)
for line in f: stream lines (best for big files)
f.write(s) write a string; returns the count; adds no \n
f.writelines(lines) write each string; adds no \n
print(..., file=f) write with \n and sep
f.seek(0), f.tell() move to / report the position
f.flush() push the buffer to the OS
from pathlib import Path
out = Path("output")
out.mkdir(exist_ok=True)
log = out / "run.txt"
with open(log, "w", encoding="utf-8") as f: # truncate, then write
f.write("first line\n")
print("second", "line", file=f)
with open(log, "a", encoding="utf-8") as f: # add at the end
f.writelines(["third\n", "fourth\n"])
with open(log, encoding="utf-8") as f:
print(f.readline().rstrip(), "|", [line.rstrip() for line in f])
words = Path("data/readings.txt").read_text(encoding="utf-8").split()
temps = [float(w) for w in words if w.replace(".", "", 1).isdecimal()] # skip "error"
print(len(words), len(temps), min(temps), max(temps))
Output
first line | ['second line', 'third', 'fourth']
42 40 19.3 22.9
from pathlib import Path
with open(Path("output/run.txt"), "x", encoding="utf-8") as f: # never overwrites
f.write("new")
Output
FileExistsError: [Errno 17] File exists: 'output/run.txt'
Situation Do
your own files write and read encoding="utf-8"
Excel CSV export read with utf-8-sig
old Windows or European files try cp1252, then latin-1; check known values
unknown encoding read bytes, try candidates; charset-normalizer guesses
bad bytes in a log errors="replace" (lossy) or "backslashreplace"
Windows line endings \r\n text mode converts them to \n on read
byte-exact processing binary mode "rb"
make UTF-8 the default everywhere PYTHONUTF8=1 or python -X utf8 (default from Python 3.15)
from pathlib import Path
legacy = Path("data/legacy_latin1.csv")
print(legacy.read_text(encoding="latin-1").splitlines()[1])
print(legacy.read_text(encoding="utf-8", errors="replace").splitlines()[1])
Path("output/bom.csv").write_text("id,city\n1,Köln\n", encoding="utf-8-sig")
print(repr(Path("output/bom.csv").read_text(encoding="utf-8")[:4])) # BOM kept
print(repr(Path("output/bom.csv").read_text(encoding="utf-8-sig")[:4])) # BOM removed
Output
SUP01,Café Müller GmbH,Köln,Germany,2015
SUP01,Caf� M�ller GmbH,K�ln,Germany,2015
'\ufeffid,'
'id,c'
Tool Does
csv.reader(f) rows as lists of strings
csv.DictReader(f) rows as dicts; the header gives the keys
csv.writer(f) writerow(list), writerows(rows)
csv.DictWriter(f, fieldnames=[...]) writeheader(), writerow(dict); extrasaction="ignore" drops extra keys
delimiter=";", quotechar='"' other dialects
quoting=csv.QUOTE_NONNUMERIC quote all text; read unquoted fields as float
csv.Sniffer().sniff(sample) guess the delimiter
newline="" required on open() for both reading and writing
import csv
from collections import defaultdict
revenue = defaultdict(float)
with open("data/sales.csv", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
print(reader.fieldnames[:5])
for row in reader: # every value is a str
revenue[row["region"]] += float(row["revenue"])
with open("output/revenue_by_region.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["region", "revenue"])
writer.writeheader()
for region, total in sorted(revenue.items()):
writer.writerow({"region": region, "revenue": f"{total:.2f}"})
with open("output/revenue_by_region.csv", newline="", encoding="utf-8") as f:
for row in csv.reader(f):
print(row)
Output
['order_id', 'order_date', 'customer_id', 'store_id', 'region']
['region', 'revenue']
['East', '993683.72']
['North', '888229.47']
['South', '891766.07']
['West', '822844.57']
import csv
import io
text = 'id;name;note\n1;"Smith; J.";"said ""hi"""\n'
print(csv.Sniffer().sniff(text).delimiter)
print(list(csv.reader(io.StringIO(text), delimiter=";")))
buffer = io.StringIO()
csv.writer(buffer).writerow(["a,b", 'quote "x"', 3])
print(buffer.getvalue(), end="")
Output
;
[['id', 'name', 'note'], ['1', 'Smith; J.', 'said "hi"']]
"a,b","quote ""x""",3
Python JSON Note
dict object keys become strings: {1: "a"} → {"1": "a"}
list, tuple array a tuple comes back as a list
str string
int, float number nan and inf are written but are not valid JSON
True, False true, false
None null
datetime, Decimal, set, Path TypeError default=str, or convert first
Function Does
json.load(f) / json.loads(s) parse a file / a string
json.dump(obj, f) / json.dumps(obj) write to a file / a string
indent=2 pretty-print
sort_keys=True stable key order
ensure_ascii=False keep é instead of \u00e9
default=str call str on unknown types
separators=(",", ":") the most compact form
json.JSONDecodeError invalid input (a ValueError); has .lineno, .colno
import json
from datetime import date
from pathlib import Path
with open("data/config.json", encoding="utf-8") as f:
config = json.load(f)
print(config["project"], config["thresholds"]["max_discount"], config["model"]["type"])
report = {"city": "Köln", "day": date(2024, 5, 1), "ids": (1, 2), 3: None}
text = json.dumps(report, default=str, ensure_ascii=False)
print(text)
print(json.loads(text)) # the tuple came back as a list, the key 3 as "3"
pretty = json.dumps(report, indent=2, default=str, ensure_ascii=False)
Path("output/report.json").write_text(pretty, encoding="utf-8")
print(Path("output/report.json").read_text(encoding="utf-8").splitlines()[:3])
Output
sales-pipeline 0.2 logistic_regression
{"city": "Köln", "day": "2024-05-01", "ids": [1, 2], "3": null}
{'city': 'Köln', 'day': '2024-05-01', 'ids': [1, 2], '3': None}
['{', ' "city": "Köln",', ' "day": "2024-05-01",']
import json
events = [{"id": 1, "level": "INFO"}, {"id": 2, "level": "ERROR"}]
with open("output/events.jsonl", "w", encoding="utf-8") as f:
for event in events:
f.write(json.dumps(event) + "\n") # JSON Lines: one object per line
with open("output/events.jsonl", encoding="utf-8") as f:
errors = [e for line in f if (e := json.loads(line))["level"] == "ERROR"]
print(errors)
try:
json.loads("{'id': 1}") # single quotes are not JSON
except json.JSONDecodeError as exc:
print(f"line {exc.lineno} col {exc.colno}: {exc.msg}")
Output
[{'id': 2, 'level': 'ERROR'}]
line 1 col 2: Expecting property name enclosed in double quotes
import pickle
from collections import Counter
state = {"counts": Counter("aab"), "seen": {1, 2}, "weights": (0.5, 0.25)}
with open("output/state.pkl", "wb") as f: # binary mode
pickle.dump(state, f)
with open("output/state.pkl", "rb") as f:
restored = pickle.load(f)
print(restored == state, type(restored["counts"]).__name__, restored["seen"])
Output
True Counter {1, 2}
import tomllib
from pathlib import Path
Path("output/settings.toml").write_text(
"""
[project]
name = "sales-pipeline"
version = "1.4.0"
[thresholds]
max_discount = 0.2
regions = ["North", "South"]
start = 2024-01-01
""",
encoding="utf-8",
)
with open("output/settings.toml", "rb") as f: # tomllib needs binary mode
settings = tomllib.load(f)
print(settings["project"], settings["thresholds"]["regions"])
print(settings["thresholds"]["start"], type(settings["thresholds"]["start"]).__name__)
Output
{'name': 'sales-pipeline', 'version': '1.4.0'} ['North', 'South']
2024-01-01 date
Fact Detail
tomllib standard library since 3.11; read only
writing TOML install tomli-w (or tomlkit to keep comments)
types strings, ints, floats, bools, dates and datetimes, arrays, tables
tomllib.loads(text) parse a string
pyproject.toml the standard project config (tooling)
Call Does
shutil.copy(src, dst) copy contents and permissions; dst can be a folder
shutil.copy2(src, dst) also copy timestamps
shutil.copytree(src, dst, dirs_exist_ok=True) copy a folder tree
shutil.move(src, dst) move a file or folder (across drives too)
shutil.rmtree(path) delete a folder tree; no undo
shutil.make_archive(base, "zip", root) create base.zip; also "gztar"
shutil.unpack_archive(file, dest) extract an archive
shutil.disk_usage(path) total, used, free bytes
shutil.which("git") full path of a program, or None
tempfile.TemporaryDirectory() a folder deleted after with
tempfile.NamedTemporaryFile(delete_on_close=False) a file you can reopen by name (3.12+)
tempfile.mkstemp(), mkdtemp() create and keep; you delete it
os.walk(top) (dirpath, dirnames, filenames) for each folder
Path(top).walk() the same with Path objects (3.12+)
os.scandir(path) fast listing with cached stat info
import shutil
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp:
root = Path(tmp)
shutil.copytree("data/reports", root / "reports")
shutil.copy2("data/stores.csv", root / "reports")
(root / "reports" / "archive").mkdir()
shutil.move(root / "reports" / "2024-01.csv", root / "reports" / "archive")
for folder, dirs, files in (root / "reports").walk():
dirs.sort() # walk subfolders in a stable order
print(folder.relative_to(root), len(files), sorted(files)[:2])
archive = shutil.make_archive(str(root / "backup"), "zip", root / "reports")
shutil.unpack_archive(archive, root / "restored")
restored = sorted(p.name for p in (root / "restored").iterdir())
print(Path(archive).name, len(restored), restored[-2:])
print("deleted:", not root.exists())
Output
reports 6 ['2024-02.csv', '2024-03.csv']
reports/archive 1 ['2024-01.csv']
backup.zip 7 ['archive', 'stores.csv']
deleted: True
import gzip
import zipfile
from pathlib import Path
with gzip.open("output/readings.txt.gz", "wt", encoding="utf-8") as f:
f.write(Path("data/readings.txt").read_text(encoding="utf-8"))
with gzip.open("output/readings.txt.gz", "rt", encoding="utf-8") as f:
print(f.readline().strip(), Path("output/readings.txt.gz").suffixes)
with zipfile.ZipFile("output/reports.zip", "w", zipfile.ZIP_DEFLATED) as zf:
for path in sorted(Path("data/reports").glob("*.csv"))[:2]:
zf.write(path, arcname=path.name)
with zipfile.ZipFile("output/reports.zip") as zf:
print(zf.namelist(), zf.read("2024-01.csv").decode("utf-8").splitlines()[0])
Output
21.0 ['.txt', '.gz']
['2024-01.csv', '2024-02.csv'] order_id,order_date,store_id,product,category,quantity,revenue
Format Good for Watch out
CSV tables for people and spreadsheets no types: every value is text; delimiters and encodings vary
JSON nested data, APIs, configs no dates, no comments; one big object must fit in memory
JSON Lines logs, streams, append-only records one object per line; no trailing commas
TOML human-edited config (pyproject.toml) read-only in the standard library
YAML config in DevOps tools needs PyYAML; use yaml.safe_load only
Parquet large typed tables (pandas, Polars, DuckDB) binary; needs pyarrow
SQLite many tables, queries, updates sqlite3 in the standard library
pickle Python-only caches you made yourself unsafe to load from others; version-fragile
Excel .xlsx business users needs openpyxl; slow for big data
Trap Symptom Fix
relative paths FileNotFoundError when you run from another folder run from the project root, or build from Path(__file__).parent
open(p, "w") silently erases the file "a" to append, "x" to protect
no encoding= works on macOS, UnicodeDecodeError on Windows encoding="utf-8" every time
CSV without newline="" blank lines between rows on Windows; broken quoted newlines open(p, "w", newline="", encoding="utf-8")
CSV values "42" is a str; "" for missing convert each column; handle ""
Excel CSV first header is '\ufeffid' encoding="utf-8-sig"
f.write(line) lines run together add "\n", or print(..., file=f)
reading after the end f.read() returns "" the second time f.seek(0) or reopen
json.dump of a datetime, set, Decimal TypeError: Object of type date is not JSON serializable default=str, or convert first
JSON keys int keys come back as str convert keys after loading
single quotes in JSON JSONDecodeError: Expecting property name enclosed in double quotes it is not JSON; fix the producer (or ast.literal_eval for Python literals)
tomllib.load(open(p)) TypeError: File must be opened in binary mode open(p, "rb")
pickle.load of a downloaded file arbitrary code runs never unpickle untrusted data
glob / iterdir order differs by OS and run sorted(...)
p.rename(target) on Windows FileExistsError if target exists p.replace(target)
shutil.rmtree on the wrong path data loss print the path and check it first; never build it from user input
TemporaryDirectory path used after with the folder is gone use it inside the block
writing into data/ raw data overwritten write to output/
string paths with \ "C:\new" contains a newline Path, raw strings or /
Path.cwd() vs script folder different when run from elsewhere Path(__file__).resolve().parent for files next to the script

The standard library ships with every Python 3.12+ install, so nothing here needs pip. This page maps each common job to its module. It gives runnable examples for the areas that no other page covers, and links to the main page for the rest. Use it for scripts, automation, web back ends and data work alike.

I want to… Use… Example
count things collections.Counter Counter(words).most_common(3)
group values under a key collections.defaultdict(list) groups[key].append(row)
a fast queue or a rolling window collections.deque(maxlen=n) window.append(x); q.popleft()
a small record class @dataclasses.dataclass @dataclass(frozen=True, slots=True)
a fixed set of named constants enum.Enum, enum.StrEnum class Status(StrEnum): OK = auto()
cut a stream into chunks itertools.batched(it, n) for chunk in batched(ids, 500):
loop over a grid of options itertools.product product(lrs, depths)
cache a slow pure function functools.cache / lru_cache @cache above the def
fix some arguments of a function functools.partial partial(round, ndigits=2)
top k items without a full sort heapq.nlargest(k, xs, key=...) nlargest(3, orders, key=itemgetter(1))
insert into a sorted list bisect.insort / bisect_left bisect_left(prices, 100)
parse or format a date datetime.date.fromisoformat, strftime f"{d:%Y-%m-%d}"
the current time, safely datetime.now(UTC) from datetime import UTC
convert between time zones zoneinfo.ZoneInfo dt.astimezone(ZoneInfo("Europe/Berlin"))
find or replace a text pattern re re.findall(r"\d+ms", line) (see regex)
exact decimal money decimal.Decimal Decimal("19.99") * 3
summary statistics of a list statistics median(xs), quantiles(xs, n=4)
reproducible random numbers random.Random(42) rng.sample(ids, 5)
build and inspect paths pathlib.Path Path("data") / "sales.csv"
list files by pattern Path.glob, Path.rglob sorted(Path("data").glob("*.csv"))
copy, move or zip files shutil shutil.copytree(src, dst, dirs_exist_ok=True)
a temporary file or folder tempfile.TemporaryDirectory() with TemporaryDirectory() as tmp:
read an environment variable os.environ.get os.environ.get("LOG_LEVEL", "INFO")
run another program subprocess.run([...], check=True) run(["git", "status"], capture_output=True)
read or write JSON json.load, json.dumps json.dumps(obj, indent=2)
read CSV rows as dicts csv.DictReader for row in csv.DictReader(f):
read a TOML config tomllib.load (binary file) with open("pyproject.toml", "rb") as f: tomllib.load(f)
a command-line interface argparse.ArgumentParser parser.add_argument("--top", type=int)
log messages with levels logging.getLogger(__name__) log.warning("rows dropped: %d", n)
run work in parallel concurrent.futures ThreadPoolExecutor().map(fetch, urls)
a local SQL database sqlite3 sqlite3.connect("data/shop.db")
split or build a URL urllib.parse urlsplit(url).query, urlencode(params)
an HTTP status name http.HTTPStatus HTTPStatus(404).phrase
wrap or shorten text textwrap textwrap.shorten(text, 40)
a unique id uuid.uuid4() str(uuid.uuid4())
a file checksum hashlib.sha256 hashlib.file_digest(f, "sha256")
a secure token or password secrets secrets.token_urlsafe(16)
time a block of code time.perf_counter() start = perf_counter()
benchmark a small snippet timeit.timeit timeit(lambda: sum(xs), number=100)
copy nested data copy.deepcopy cfg2 = copy.deepcopy(cfg)
Module What for Key functions and classes
collections specialized containers Counter, defaultdict, deque, namedtuple, ChainMap, OrderedDict
itertools lazy iteration building blocks chain, islice, batched, groupby, accumulate, pairwise, product, combinations
functools higher-order functions cache, lru_cache, partial, reduce, wraps, cached_property, singledispatch
operator operators as functions itemgetter, attrgetter, methodcaller, add, mul
heapq priority queues heappush, heappop, nlargest, nsmallest, merge
bisect binary search in sorted lists bisect_left, bisect_right, insort
copy copies of objects copy (shallow), deepcopy, replace (3.13+)
dataclasses record classes without boilerplate dataclass, field, asdict, astuple, replace, fields
enum named constants Enum, StrEnum, IntEnum, Flag, auto
typing type hints TypedDict, Protocol, Literal, Self, cast (see type hints)
contextlib with helpers contextmanager, suppress, closing, ExitStack, chdir
datetime dates, times, durations date, datetime, timedelta, UTC, fromisoformat, strptime
zoneinfo IANA time zones ZoneInfo("America/Chicago")
time clocks and sleeping perf_counter, monotonic, time, sleep
timeit micro-benchmarks timeit, repeat, python -m timeit
re regular expressions search, fullmatch, findall, finditer, sub, split, compile
string character sets and templates ascii_letters, digits, punctuation, Template
textwrap wrapping and indenting text wrap, fill, shorten, dedent, indent
difflib text differences and fuzzy matches get_close_matches, unified_diff, SequenceMatcher
unicodedata Unicode normalization normalize("NFKC", s), name, category
math float math sqrt, log, isclose, fsum, prod, comb, inf, nan
statistics descriptive statistics mean, median, stdev, quantiles, correlation, NormalDist
random pseudo-random numbers Random(seed), choice, choices, sample, shuffle, gauss
decimal, fractions exact arithmetic Decimal("0.10"), quantize, Fraction(1, 3)
os the operating system environ, getenv, cpu_count, scandir, getpid
sys the interpreter argv, exit, executable, path, version_info, stdin, stderr
pathlib paths as objects Path, /, glob, rglob, read_text, mkdir, stem, suffix
shutil high-level file operations copy2, copytree, move, rmtree, make_archive, which
tempfile temporary files and folders TemporaryDirectory, NamedTemporaryFile, mkdtemp
glob, fnmatch shell-style patterns glob("**/*.py", recursive=True), fnmatch(name, "*.csv")
subprocess run other programs run, CalledProcessError, TimeoutExpired
json JSON text load, loads, dump, dumps(indent=2, default=str)
csv CSV files reader, writer, DictReader, DictWriter
tomllib read TOML (read only) load(binary_file), loads(text)
pickle Python object files (trusted data only) dump, load
zipfile, gzip, tarfile archives and compression ZipFile, gzip.open, tarfile.open
argparse command-line interfaces ArgumentParser, add_argument, add_subparsers, parse_args
logging leveled log messages getLogger, basicConfig, Handler, Formatter, exception
warnings soft deprecations warn, catch_warnings, simplefilter
traceback format errors print_exc, format_exception
concurrent.futures thread and process pools ThreadPoolExecutor, ProcessPoolExecutor, as_completed
threading, multiprocessing low-level concurrency Thread, Lock, Event, Process, Pool
asyncio asynchronous I/O run, gather, TaskGroup, Semaphore, timeout, to_thread
queue thread-safe queues Queue, put, get, task_done
sqlite3 an embedded SQL database connect, execute, executemany, Row, commit
urllib.parse URLs urlsplit, urljoin, urlencode, parse_qs, quote
urllib.request simple HTTP requests urlopen, Request
http HTTP constants and a test server HTTPStatus, python -m http.server
uuid unique ids uuid4, UUID, uuid7 (3.14+)
hashlib checksums and hashes sha256, md5, file_digest, hexdigest
hmac signed messages hmac.new(key, msg, "sha256"), compare_digest
secrets security tokens token_hex, token_urlsafe, choice, compare_digest
base64 binary as text b64encode, urlsafe_b64decode
importlib.metadata installed package versions version("pandas"), packages_distributions
pprint readable nested output pp, pformat
inspect look at live objects signature, getsource, isfunction, iscoroutinefunction
configparser INI-style config files ConfigParser, read, getint, getboolean
xml.etree.ElementTree parse and build XML parse, fromstring, find, findall, iter
html HTML escaping escape, unescape; html.parser.HTMLParser
ipaddress IP addresses and networks ip_address, ip_network, addr in network
shlex shell-like splitting and quoting split("a 'b c'"), quote, join
struct binary records pack, unpack, calcsize
weakref references that do not keep objects alive ref, WeakValueDictionary, finalize
platform OS and machine details system, machine, python_version
getpass read a password without echo getpass, getuser
signal handle OS signals signal(SIGTERM, handler), SIGINT
graphlib dependency ordering TopologicalSorter(graph).static_order()
calendar calendars and month facts monthrange, isleap, month_name
email, smtplib build and send mail email.message.EmailMessage, smtplib.SMTP_SSL

Several standard library modules have their own master cheat sheet page. This page only lists them in the module map.

Topic Modules Main page
containers, top k, sorted lists collections, heapq, bisect collections module, heapq and bisect
lazy iteration, chunks, combinations itertools itertools
partial, reduce, key functions functools, operator map, filter, reduce and partial, key functions
caching, wraps, contextmanager functools, contextlib decorators and context managers
paths, files, folders pathlib, shutil, tempfile pathlib, shutil, tempfile and walking folders
JSON, CSV, TOML, pickle json, csv, tomllib, pickle JSON, CSV, TOML
strftime codes datetime dates and times in f-strings
regular expressions re regex
logging, tracebacks, warnings logging, traceback, warnings, pdb logging
record classes dataclasses, typing.NamedTuple data containers
named constants enum enums
interfaces abc, typing.Protocol ABC vs Protocol
type hints typing, collections.abc type hints
thread and process pools, async concurrent.futures, threading, asyncio, queue performance and concurrency
timeit, cProfile, tracemalloc in depth timeit, cProfile, pstats measure
from datetime import UTC, date, datetime, timedelta
from zoneinfo import ZoneInfo
d = date.fromisoformat("2024-05-01")
print(d.strftime("%a %d %b %Y"), d.isocalendar().week, d + timedelta(days=30))
parsed = datetime.strptime("01/05/2024 08:25", "%d/%m/%Y %H:%M") # day first
print(parsed.isoformat())
logged = datetime(2024, 5, 1, 13, 25, tzinfo=UTC) # store aware UTC times
print(f"{logged.astimezone(ZoneInfo('America/Chicago')):%H:%M %Z}")
print((datetime(2024, 5, 2, tzinfo=UTC) - logged) // timedelta(hours=1), "hours")
Output
Wed 01 May 2024 18 2024-05-31
2024-05-01T08:25:00
08:25 CDT
10 hours

The strftime codes are on the strings page.

import difflib
import re
import string
import textwrap
line = "2024-05-01 08:04:01,354 INFO [api] 10.0.3.17 GET /api/v1/reports 200 87ms"
m = re.search(r"(?P<method>GET|POST) (?P<path>\S+) (?P<status>\d{3})", line)
print(m["method"], m["path"], int(m["status"]))
print(string.ascii_lowercase[:5], string.digits, len(string.punctuation))
print(string.Template("Hello $name").substitute(name="Ada")) # safe user templates
print(textwrap.shorten("Cotton Bed Sheet Set, queen size, white", width=24))
print(textwrap.dedent(" a\n b").splitlines())
print(difflib.get_close_matches("Chicgo", ["Chicago", "Houston", "Boston"]))
Output
GET /api/v1/reports 200
abcde 0123456789 32
Hello Ada
Cotton Bed Sheet [...]
['a', ' b']
['Chicago']

The full regex syntax and the re functions are on the regex page.

Numbers: math, statistics, random and decimal

Section titled “Numbers: math, statistics, random and decimal”
import math
import random
import statistics
from decimal import ROUND_HALF_UP, Decimal
from fractions import Fraction
print(math.isclose(0.1 + 0.2, 0.3), math.fsum([0.1] * 10), math.comb(5, 2))
latencies = [87, 88, 93, 31, 42, 45, 32, 44, 1188]
print(statistics.median(latencies), round(statistics.mean(latencies), 1))
print(statistics.quantiles(latencies, n=4)) # quartile cut points
rng = random.Random(42) # a private, seeded generator
print(rng.randint(1, 6), rng.choice(["S01", "S02", "S03"]), rng.sample(range(10), 3))
price = Decimal("2.675")
print(price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP), round(2.675, 2))
print(Fraction(1, 3) + Fraction(1, 6))
Output
True 1.0 10
45 183.3
[37.0, 45.0, 90.5]
6 S01 [0, 4, 3]
2.68 2.67
1/2

The OS: os, sys, shutil, tempfile and subprocess

Section titled “The OS: os, sys, shutil, tempfile and subprocess”
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
print(os.environ.get("APP_MODE", "dev"), sys.version_info >= (3, 12))
with tempfile.TemporaryDirectory() as tmp: # deleted after the block
out = Path(tmp) / "backup"
shutil.copytree("data/reports", out)
print(sorted(p.name for p in out.iterdir())[:2])
result = subprocess.run(
[sys.executable, "-c", "print(6 * 7)"], # a list, never a shell string
capture_output=True, text=True, check=True,
)
print(result.returncode, result.stdout.strip())
Output
dev True
['2024-01.csv', '2024-02.csv']
0 42

The full pathlib reference is on the files and formats page.

import argparse
parser = argparse.ArgumentParser(prog="report", description="Summarize a log file.")
parser.add_argument("path")
parser.add_argument("--level", choices=["INFO", "WARNING", "ERROR"], default="INFO")
parser.add_argument("-n", "--top", type=int, default=5)
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args(["data/logs/app.log", "--top", "3", "--dry-run"])
print(args.path, args.level, args.top, args.dry_run) # --dry-run -> dry_run
Output
data/logs/app.log INFO 3 True

Logging setup, levels and handlers are on the errors and debugging page.

import sqlite3
with sqlite3.connect("file:data/shop.db?mode=ro", uri=True) as conn: # read-only
conn.row_factory = sqlite3.Row # rows behave like dicts
rows = conn.execute(
"SELECT region, COUNT(*) AS n FROM stores WHERE size_sqm > ? GROUP BY region "
"ORDER BY region",
(2000,), # parameters: never format values into SQL
).fetchall()
print([(r["region"], r["n"]) for r in rows])
mem = sqlite3.connect(":memory:")
mem.execute("CREATE TABLE t (id TEXT PRIMARY KEY, qty INTEGER)")
with mem: # commits on success, rolls back on an error
mem.executemany("INSERT INTO t VALUES (?, ?)", [("a", 2), ("b", 5)])
print(mem.execute("SELECT SUM(qty) FROM t").fetchone()[0])
mem.close() # `with conn:` manages the transaction, not the connection
Output
[('East', 2), ('North', 1), ('South', 2), ('West', 1)]
7
from http import HTTPStatus
from urllib.parse import parse_qs, quote, urlencode, urljoin, urlsplit
url = "https://api.example.com/api/v1/products?page=2&category=Home"
parts = urlsplit(url)
print(parts.netloc, parts.path, parse_qs(parts.query))
print(urlencode({"q": "bed sheet", "page": 3}), quote("a b/c", safe=""))
print(urljoin("https://api.example.com/api/v1/", "products/P026"))
print(HTTPStatus(429).phrase, HTTPStatus.NOT_FOUND.value,
HTTPStatus(503).is_server_error)
Output
api.example.com /api/v1/products {'page': ['2'], 'category': ['Home']}
q=bed+sheet&page=3 a%20b%2Fc
https://api.example.com/api/v1/products/P026
Too Many Requests 404 True
needs the network
import json
from urllib.request import Request, urlopen
req = Request("https://api.example.com/api/v1/products", headers={"Accept": "application/json"})
with urlopen(req, timeout=10) as resp: # raises HTTPError for 4xx and 5xx
data = json.load(resp)

For real API work, httpx or requests handle sessions, retries and JSON more simply: see module 16: APIs and web data.

Ids and security: uuid, hashlib and secrets

Section titled “Ids and security: uuid, hashlib and secrets”
import hashlib
import secrets
import uuid
run_id = uuid.uuid4() # random; different on every run
print(len(str(run_id)), run_id.version)
print(hashlib.sha256(b"sales-pipeline").hexdigest()[:16]) # same input, same hash
with open("data/stores.csv", "rb") as f:
print(hashlib.file_digest(f, "sha256").hexdigest()[:16]) # file checksum
token = secrets.token_urlsafe(16) # for reset links, API keys
print(len(token) >= 16, secrets.compare_digest("abc", "abc"))
Output
36 4
d4feb518a643f218
0ca4294e9a1ab317
True True
Need Use Not
a password reset token, API key secrets.token_urlsafe(32) random (predictable)
store a password hashlib.scrypt(pw, salt=..., n=2**14, r=8, p=1) or a library such as argon2 a plain sha256
check a file download hashlib.file_digest(f, "sha256") md5 for security
compare secrets secrets.compare_digest(a, b) == (leaks timing)
a database key uuid.uuid4(); uuid.uuid7() (3.14+, time-ordered) id(obj)
import time
import timeit
values = list(range(10_000))
start = time.perf_counter() # a monotonic, high-resolution clock
total = sum(values)
elapsed = time.perf_counter() - start
per_call = timeit.timeit(lambda: sum(values), number=200) / 200
print(total, elapsed >= 0, per_call < 0.01) # print comparisons, not raw timings
Output
49995000 True True
Clock Use
time.perf_counter() durations and benchmarks
time.monotonic() timeouts; never goes backward
time.time() a Unix timestamp; can jump when the clock is set
time.process_time() CPU time of this process only
datetime.now(UTC) a timestamp to store or show
Trap Symptom Fix
a file named random.py, json.py or logging.py AttributeError: module 'random' has no attribute ... rename your file; it shadows the module
datetime.now() without a zone naive local time; differs per machine datetime.now(UTC)
naive and aware datetimes mixed TypeError: can't compare offset-naive and offset-aware datetimes make all of them aware in UTC
%m/%d versus %d/%m 1 May read as 5 January, no error test a day above 12
subprocess.run("cmd " + user_input, shell=True) shell injection a list of arguments, no shell
subprocess.run without check=True a failing command passes silently check=True
with sqlite3.connect(...) as conn commits, but does not close the connection conn.close() or contextlib.closing
SQL built with f-strings SQL injection, quoting bugs ? placeholders and a parameter tuple
random for tokens predictable values secrets
random.seed(42) with the global functions other code shifts your sequence rng = random.Random(42)
@dataclass with items: list = [] ValueError: mutable default ... is not allowed field(default_factory=list)
ZoneInfo on Windows ZoneInfoNotFoundError pip install tzdata
secrets.compare_digest skipped == on tokens leaks timing information secrets.compare_digest(a, b)

Traps of modules that have their own page are listed there: collections, itertools, files and formats, logging, functools caching.

A regular expression (regex) is a small pattern language for text: find, validate, extract, split and replace. This page covers Python’s re syntax and functions, with examples on the course log file data/logs/app.log, and the pandas .str methods that take the same patterns.

I want to… Use… Example
test if a pattern occurs anywhere re.search(p, s) if re.search(r"\bERROR\b", line):
test if a pattern starts the string re.match(p, s) re.match(r"\d{4}-\d{2}-\d{2}", line)
validate a whole value re.fullmatch(p, s) re.fullmatch(r"P\d{3}", pid)
get every match as strings re.findall(p, s) re.findall(r"\d+ms", text)
get every match with positions and groups re.finditer(p, s) for m in re.finditer(p, text):
replace matches re.sub(p, repl, s) re.sub(r"\s+", " ", s)
replace with computed text re.sub(p, func, s) re.sub(r"\d+", lambda m: str(int(m[0]) * 2), s)
count replacements re.subn(p, repl, s) new, n = re.subn(...)
split on a pattern re.split(p, s) re.split(r"[;,]\s*", "a, b;c")
reuse a pattern re.compile(p, flags) LINE = re.compile(r"...")
match a literal string safely re.escape(s) re.search(re.escape("1.5 (x)"), s)
capture a part (...) and m[1] re.search(r"(\d+)ms", line)[1]
capture with a name (?P<name>...) and m["name"] m["status"]
group without capturing (?:...) (?:GET|POST) /\S+
one of several words \b(?:a|b|c)\b \b(?:WARNING|ERROR)\b
match the shortest text a lazy quantifier *?, +? <.+?>
require text after, without taking it lookahead (?=...) \d+(?=ms)
forbid text after negative lookahead (?!...) \buser=(?!-)\S+
require text before lookbehind (?<=...) (?<=user=)\S+
ignore case re.IGNORECASE or (?i) re.search(r"error", s, re.I)
^ and $ at every line re.MULTILINE re.findall(r"^\S+", text, re.M)
. across newlines re.DOTALL re.search(r"Traceback.*?Error", text, re.S)
a readable, commented pattern re.VERBOSE spaces and # comments inside the pattern
a dict of named groups m.groupdict() {"method": "GET", ...}
swap parts in a replacement \1, \g<name> re.sub(r"(\d+)/(\d+)", r"\2/\1", s)
extract columns in pandas s.str.extract(p) named groups become column names
filter rows in pandas s.str.contains(p) df[df["line"].str.contains(r"\bERROR\b")]

Write every pattern as a raw string r"...". In a normal string, Python handles backslashes before re sees them: "\b" is a backspace character, and "\d" is an invalid escape that triggers a SyntaxWarning.

import re
print(len("\b"), len(r"\b")) # 1 character vs 2 characters
print(re.findall(r"\bms\b", "87ms 93 ms"), re.findall("\bms\b", "87ms 93 ms"))
print(re.escape("price (USD) 1.5")) # escape text you want to match literally
Output
1 2
['ms'] []
price\ \(USD\)\ 1\.5
Pattern Matches Example → match
a, 7, - that literal character r"GET" → GET
. any character except \n (with re.S, also \n) r"a.c" → abc, a-c
\d / \D a digit / a non-digit (Unicode digits too) r"\d\d" → 87
\w / \W a word character [a-zA-Z0-9_] plus Unicode letters / other r"\w+" → user_42
\s / \S whitespace (space, tab, newline) / other r"\S+" → one token
[abc] one of the listed characters r"[aeiou]"
[a-z0-9] a range r"[A-F0-9]+" → hex
[^abc] any character not listed r"[^,]+" → one CSV field
[.], [$], [*] most special characters are literal inside [] r"[.]" → .
\., \*, \(, \[, \\ an escaped literal r"1\.5" → 1.5
\t, \n tab, newline
\b / \B a word boundary / not a boundary (zero width) r"\bINFO\b"
Greedy Lazy Possessive (3.11+) Repeats
* *? *+ 0 or more
+ +? ++ 1 or more
? ?? ?+ 0 or 1
{n} exactly n
{m,n} {m,n}? {m,n}+ m to n
{m,} {m,}? {m,}+ m or more

Greedy takes as much as it can, then backs off. Lazy takes as little as it can. Possessive takes as much as it can and never backs off (faster failures, fewer matches).

import re
html = "<b>Wireless</b> <i>Earbuds</i>"
print(re.findall(r"<.+>", html)) # greedy: one match spans everything
print(re.findall(r"<.+?>", html)) # lazy: each tag
print(re.findall(r"<[^>]+>", html)) # a negated class: often the clearest
print(re.findall(r"\d{2,3}", "7 87 1188"), re.findall(r"\d{2,3}?", "1188"))
Output
['<b>Wireless</b> <i>Earbuds</i>']
['<b>', '</b>', '<i>', '</i>']
['<b>', '</b>', '<i>', '</i>']
['87', '118'] ['11', '88']
Pattern Matches at Note
^ the start of the string with re.M: the start of every line
$ the end of the string, or before a final \n with re.M: the end of every line
\A the start of the string only ignores re.M
\Z the end of the string only ignores re.M
\b a word boundary between \w and \W
Pattern Meaning
(...) capturing group; numbered from 1 by its opening parenthesis
(?P<name>...) named group; read with m["name"]
(?:...) group without a capture (for | or a quantifier)
a|b a or b; the leftmost alternative that matches wins
\1, (?P=name) the same text again, inside the pattern
\1, \g<1>, \g<name> a group’s text in a sub replacement
(?>...) atomic group (3.11+): never backtracks into it
(?(1)yes|no) conditional: yes if group 1 matched
Pattern Means Example → match
X(?=Y) X followed by Y r"\d+(?=ms)" on 93ms → 93
X(?!Y) X not followed by Y r"\b\d+\b(?!ms)"
(?<=Y)X X preceded by Y r"(?<=user=)\S+" → the user
(?<!Y)X X not preceded by Y r"(?<!-)\b\d+" → positive numbers

A lookbehind must have a fixed width in Python’s re: (?<=user=) works, (?<=\w+=) raises re.error.

import re
line = "17:18:02,430 ERROR [api] 198.51.100.23 POST /api/v1/predict 500 1188ms"
print(re.findall(r"\d+(?=ms)", line)) # the number before "ms", without "ms"
print(re.search(r"(?<=\[)\w+(?=\])", line)[0]) # the text inside [ ]
pw = re.compile(r"(?=.*\d)(?=.*[A-Z]).{8,}") # several conditions at once
print([bool(pw.fullmatch(p)) for p in ["secret12", "Secret12", "Sh0rt"]])
Output
['1188']
api
[False, True, False]
Flag Inline Effect
re.IGNORECASE, re.I (?i) case-insensitive
re.MULTILINE, re.M (?m) ^ and $ at each line
re.DOTALL, re.S (?s) . also matches \n
re.VERBOSE, re.X (?x) whitespace ignored, # starts a comment
re.ASCII, re.A (?a) \w, \d, \s, \b match ASCII only
combine (?im) re.I | re.M
scoped (?i:...), (?-i:...) turn a flag on or off for that group only

Pass flags with a keyword: re.sub(p, repl, s, flags=re.I). The fourth positional argument of re.sub is count, not flags. Python 3.13 deprecates passing count and flags by position.

Function Returns Use for
re.search(p, s) the first Match anywhere, or None “does it contain…?”
re.match(p, s) a Match at position 0, or None prefixes
re.fullmatch(p, s) a Match of the whole string, or None validation
re.findall(p, s) a list of strings; with 1 group its text; with 2+ groups tuples quick extraction
re.finditer(p, s) an iterator of Match objects positions, named groups, large texts
re.sub(p, repl, s, count=0, flags=0) the new string cleaning, masking
re.subn(p, repl, s) (new_string, number_of_replacements) reporting changes
re.split(p, s, maxsplit=0) a list of pieces; captured groups are kept tokenizing
re.compile(p, flags) a Pattern with the same methods reuse; pos and endpos arguments
re.escape(s) s with special characters escaped user input inside a pattern
Match member Gives
m[0], m.group() the whole match
m[1], m["name"], m.group(1, 2) one group, or a tuple of groups
m.groups() all groups as a tuple (None where a group did not take part)
m.groupdict() named groups as a dict
m.start(), m.end(), m.span(g) positions in the string
m.expand(r"\2-\1") a template filled with the groups
bool(m) always True; test if m: or if m is None:
import re
text = "a=1, b=22; c=333"
print(re.findall(r"\d+", text)) # no group: whole matches
print(re.findall(r"(\w)=(\d+)", text)) # 2 groups: tuples
print(re.split(r"[,;]\s*", text), re.split(r"([,;])\s*", text)) # groups kept
print(re.sub(r"(\w)=(\d+)", r"\2=\1", text)) # backreferences
print(re.subn(r"\d", "#", text))
print(re.sub(r"\d+", lambda m: str(int(m[0]) * 2), text)) # computed replacement
m = re.fullmatch(r"(?P<key>\w)=(?P<value>\d+)", "b=22")
print(m.groupdict(), m.span("value"), re.match(r"\d", text))
Output
['1', '22', '333']
[('a', '1'), ('b', '22'), ('c', '333')]
['a=1', 'b=22', 'c=333'] ['a=1', ',', 'b=22', ';', 'c=333']
1=a, 22=b; 333=c
('a=#, b=##; c=###', 6)
a=2, b=44; c=666
{'key': 'b', 'value': '22'} (2, 4) None

The log lines look like this:

data/logs/app.log (excerpt)
2024-05-01 08:04:01,354 INFO [api] 10.0.3.17 GET /api/v1/reports/2024-04 200 87ms user=priya.nair@example.com
2024-05-01 08:25:14,977 WARNING [validator] 23 rows with missing customer_id in sales_raw.csv
2024-05-01 10:53:56,110 ERROR [loader] Failed to parse data/reports/2024-04.csv
Traceback (most recent call last):

Parse request lines with a verbose pattern

Section titled “Parse request lines with a verbose pattern”
import re
from collections import Counter
from pathlib import Path
text = Path("data/logs/app.log").read_text(encoding="utf-8")
API = re.compile(
r"""
^(?P<date>\d{4}-\d{2}-\d{2})\s(?P<time>[\d:]{8}),\d{3}\s
(?P<level>[A-Z]+)\s\[api\]\s
(?P<ip>\d{1,3}(?:\.\d{1,3}){3})\s
(?P<method>GET|POST|PUT|DELETE)\s(?P<path>\S+)\s
(?P<status>\d{3})\s(?P<ms>\d+)ms\s
user=(?P<user>\S+)$
""",
re.VERBOSE | re.MULTILINE, # spaces ignored; ^ and $ per line
)
requests = [m.groupdict() for m in API.finditer(text)]
print(len(requests), requests[0]["method"], requests[0]["path"], requests[0]["ms"])
print(Counter(r["status"] for r in requests).most_common(3))
slow = [r for r in requests if int(r["ms"]) >= 1000]
print(len(slow), sorted({r["path"] for r in slow}))
Output
391 GET /api/v1/reports/2024-04 87
[('200', 250), ('201', 77), ('429', 13)]
2 ['/api/v1/predict', '/api/v1/products?page=2']
levels = Counter(re.findall(r"^\S+ \S+ (DEBUG|INFO|WARNING|ERROR)\b", text, re.M))
print(sorted(levels.items()))
errors = re.findall(r"^.* ERROR \[(\w+)\] (.*)$", text, re.MULTILINE)
print(len(errors), errors[0])
line = text.splitlines()[0]
print(re.sub(r"(?<=user=)[^@\s]+@", "***@", line).split()[-1]) # keep the domain
users = set(re.findall(r"user=([\w.+-]+@[\w-]+\.\w+)", text))
print(len(users), sorted(users)[:2])
Output
[('DEBUG', 13), ('ERROR', 7), ('INFO', 447), ('WARNING', 25)]
7 ('db', 'OperationalError: database is locked (attempt 1/3), retrying in 1s')
user=***@example.com
8 ['ana.silva@example.com', 'diego.ramos@example.net']
tb = re.compile(r"^Traceback.*?^(\w+Error): ([^\n]*)", re.MULTILINE | re.DOTALL)
for m in tb.finditer(text): # lazy .*? stops at the first error line
# with DOTALL, a greedy (.*) here would run to the end of the file
print(m[1], "|", m[2][:45])
Output
ValueError | Usecols do not match columns, columns expecte
ValueError | Usecols do not match columns, columns expecte

pandas string methods take the same patterns. They work on a whole column at once. The full .str reference is on the pandas page.

Method Regex by default? Returns
s.str.contains(p, case=True, regex=True) yes a boolean Series (for filtering)
s.str.match(p) / s.str.fullmatch(p) yes boolean: anchored at the start / whole value
s.str.extract(p) yes a DataFrame: one column per group; named groups name the columns
s.str.extractall(p) yes one row per match (a MultiIndex with match)
s.str.findall(p) yes a list of matches per row
s.str.count(p) yes the number of matches per row
s.str.replace(p, repl, regex=True) no: pass regex=True new strings; repl may be a function
s.str.split(p, regex=True, expand=True) only for patterns longer than 1 character lists or columns
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
lines = pd.Series(text.splitlines(), dtype="str")
api = lines[lines.str.contains(r"\[api\]")]
pattern = r"(?P<method>GET|POST) (?P<path>\S+) (?P<status>\d{3}) (?P<ms>\d+)ms"
parts = api.str.extract(pattern) # named groups -> column names
parts["ms"] = parts["ms"].astype(int)
print(parts.groupby("method")["ms"].median())
print(api.str.replace(r"user=\S+", "user=***", regex=True).iloc[0][-40:])
Output
method
GET 32.0
POST 88.0
Name: ms, dtype: float64
api/v1/reports/2024-04 200 87ms user=***
Data Pattern Note
ISO date \d{4}-\d{2}-\d{2} format only; validate with date.fromisoformat
time 08:04:01 \d{2}:\d{2}:\d{2}
integer, optional sign [-+]?\d+
decimal number [-+]?\d+(?:\.\d+)? add (?:[eE][-+]?\d+)? for 1e3
money such as $1,299.00 \$(\d{1,3}(?:,\d{3})*\.\d{2}) remove commas before float()
an id such as O000123 \bO\d{6}\b \b stops partial matches
simple email [\w.+-]+@[\w-]+(?:\.[\w-]+)+ real validation: send a mail
IPv4 address \b\d{1,3}(?:\.\d{1,3}){3}\b use ipaddress.ip_address() to validate
URL path and query (/[^\s?]*)(?:\?(\S*))? use urllib.parse.urlsplit for full URLs
key=value pairs (\w+)=(\S+) dict(re.findall(...))
quoted string "([^"\\]*(?:\\.[^"\\]*)*)" handles \" inside
repeated whitespace \s+ → " " " ".join(s.split()) is simpler
a word from a list \b(?:INFO|WARNING|ERROR)\b build with "|".join(map(re.escape, words))
blank lines ^\s*$ with re.M
Trap Symptom Fix
a pattern without r"..." \b never matches; SyntaxWarning: invalid escape sequence always use raw strings
re.match for “contains” None although the text is there re.search; fullmatch for validation
re.search for validation "P0011" passes P\d{3} re.fullmatch, or anchor with \A...\Z (not $, which accepts a trailing newline)
findall with groups returns group text or tuples, not the whole match (?:...) for non-capturing groups, or finditer
greedy .* one match swallows several fields or tags .*?, or a negated class [^,]*
. and newlines a multi-line block does not match re.DOTALL
^ and $ match only once in a multi-line text re.MULTILINE
re.sub(p, r, s, re.I) the flag is taken as count flags=re.I
a None match TypeError: 'NoneType' object is not subscriptable test if m: before m[1]
user input in a pattern re.error or wrong matches on . ( + re.escape(user_text)
a backslash in a sub replacement re.error: bad escape double it, or use a function as repl
\d matches Unicode digits "٣" passes \d re.ASCII or [0-9]
variable-width lookbehind re.error: look-behind requires fixed-width pattern capture a group instead
nested quantifiers such as (a+)+ catastrophic backtracking: the program hangs simplify; atomic groups or possessive quantifiers
regex for HTML, JSON or CSV breaks on nesting and quoting html.parser/BeautifulSoup, json, csv
pandas str.replace the pattern is treated as plain text pass regex=True
pandas str.contains with (, . or ? in plain text wrong matches or a warning about groups regex=False for literal text

Type hints describe what a function takes and returns. Python stores them and ignores them at runtime. A static type checker such as mypy or pyright reads them and finds bugs before the code runs. This page uses the Python 3.12+ syntax.

I want to… Use… Example
hint parameters and the return value name: T, -> R def mean(xs: list[float]) -> float:
say “returns nothing” -> None def log(msg: str) -> None:
hint an empty container a variable annotation rows: list[dict[str, str]] = []
allow None T | None def find(cid: str) -> Customer | None:
allow several types a union A | B value: int | float | str
a fixed-length tuple / any length tuple[str, float] / tuple[float, ...] def span() -> tuple[int, int]:
accept any iterable or sequence Iterable[T], Sequence[T] def total(xs: Iterable[float]) -> float:
accept any read-only mapping Mapping[K, V] def show(cfg: Mapping[str, object]) -> None:
type a generator Iterator[T] or Generator[Y, S, R] def lines(p: Path) -> Iterator[str]:
type a callback Callable[[A, B], R] on_done: Callable[[str], None]
allow only some constant values Literal[...] mode: Literal["r", "w"]
type a JSON-like dict TypedDict class Order(TypedDict): order_id: str
a key that may be absent NotRequired[T] phone: NotRequired[str]
name a long type type alias type Row = dict[str, str | float]
keep the item type through a function a type parameter def first[T](xs: Sequence[T]) -> T:
a generic class class Name[T]: class Stack[T]:
limit a type parameter a bound or constraints def top[N: float](xs: list[N]) -> N:
accept “anything with method m” Protocol class Readable(Protocol): def read(self) -> str: ...
return the instance’s own class Self def fit(self, X) -> Self:
keep a decorated function’s signature ParamSpec via [**P, R] def timed[**P, R](f: Callable[P, R]) -> Callable[P, R]:
several signatures for one function @overload def get(k: str) -> str: ...
a constant that is never reassigned Final MAX_RETRIES: Final = 3
a class-level attribute ClassVar[T] registry: ClassVar[dict[str, type]] = {}
mark a method as an override @override (3.12+) @override def run(self) -> None:
narrow with your own check TypeIs[T] (3.13+), TypeGuard[T] def is_str(x: object) -> TypeIs[str]:
prove every case is handled assert_never(x) the else of a match or if chain
a function that never returns NoReturn (or Never) def fail(msg: str) -> NoReturn: raise SystemExit(msg)
an async callback Callable[[str], Awaitable[None]] on_page: Callable[[int], Coroutine[Any, Any, str]]
only literal strings (SQL, shell) LiteralString def run(sql: LiteralString) -> None: (pyright enforces it; mypy treats it as str)
a type you know but the checker does not cast(T, value) cast(Config, json.load(f))
imports only for hints if TYPE_CHECKING: avoids import cycles and slow imports
a distinct type for ids NewType UserId = NewType("UserId", int)
extra metadata on a type Annotated[T, meta] Annotated[int, Field(gt=0)] (pydantic)
silence one checker error # type: ignore[code] x = legacy() # type: ignore[no-untyped-call]
check a project mypy src/ mypy --strict src/
Feature Modern syntax Old spelling (still valid)
built-in generics list[int], dict[str, float], set[str], tuple[int, ...] typing.List[int], Dict, Set, Tuple
optional str | None Optional[str]
union int | str Union[int, str]
callables collections.abc.Callable[[int], str] typing.Callable
abstract containers collections.abc.Iterable, Sequence, Mapping, Iterator typing.Iterable and others
literal values Literal["mean", "median"]
a dict with known keys class Order(TypedDict): ... TypedDict("Order", {...})
a structural interface class P(Protocol): ...
type alias type Matrix = list[list[float]] Matrix: TypeAlias = list[list[float]]
generic function def first[T](xs: list[T]) -> T: T = TypeVar("T")
bound def f[N: float](x: N) -> N: TypeVar("N", bound=float)
constrained def f[S: (str, bytes)](x: S) -> S: TypeVar("S", str, bytes)
generic class class Box[T]: class Box(Generic[T]):
generic alias type Pair[T] = tuple[T, T]
parameter spec def deco[**P, R](f: Callable[P, R]) -> Callable[P, R]: P = ParamSpec("P")
variadic generics def f[*Ts](*args: *Ts) -> tuple[*Ts]: TypeVarTuple("Ts")
type parameter default (3.13+) class Box[T = int]: TypeVar("T", default=int)
own class Self a bound TypeVar
typed **kwargs **kwargs: Unpack[Options] with a TypedDict
deprecation marker (3.13+) @warnings.deprecated("use g()")

Import abstract types from collections.abc. Import Literal, TypedDict, Protocol, Self, Final, ClassVar, cast, overload, TYPE_CHECKING and friends from typing.

from collections.abc import Iterable, Iterator, Sequence
def mean(xs: Sequence[float]) -> float: # accept general input
return sum(xs) / len(xs)
def parse(values: Iterable[str]) -> list[float | None]: # return specific output
return [float(v) if v.strip() else None for v in values]
def chunks(xs: list[int], size: int = 2) -> Iterator[list[int]]:
for i in range(0, len(xs), size):
yield xs[i : i + size]
def label(code: str | None) -> str:
if code is None: # the checker narrows code to str below
return "none"
return code.upper()
print(mean([3, 4.5]), parse(["21.5", " "]), list(chunks([1, 2, 3])), label(None))
print(mean.__annotations__) # hints are stored, not enforced
Output
3.75 [21.5, None] [[1, 2], [3]] none
{'xs': collections.abc.Sequence[float], 'return': <class 'float'>}
Hint Accepts Note
float float and int int is accepted where float is expected
list[float] a list of floats invariant: a list[int] variable is rejected
Sequence[float] a list, tuple or range of floats or ints read-only and covariant: list[int] is fine; a str is a Sequence[str]
Iterable[T] anything you can loop over once generators, files, sets
Mapping[str, V] any dict-like, read-only use dict[str, V] when you mutate
object anything; allows nothing until narrowed a safe “any value”
Any anything; allows everything switches checking off
type[Model] the class itself, not an instance factories

Rule of thumb: accept general types (Iterable, Sequence, Mapping), return specific ones (list, dict).

from typing import Final, Literal, NotRequired, TypedDict, get_type_hints
type Channel = Literal["online", "store"]
TAX_RATE: Final = 0.2 # mypy flags any reassignment
class Order(TypedDict):
order_id: str
channel: Channel
revenue: float
coupon: NotRequired[str] # the key may be absent
order: Order = {"order_id": "O000001", "channel": "online", "revenue": 66.49}
print(order.get("coupon", "none"), type(order).__name__) # a plain dict at runtime
print(sorted(Order.__required_keys__), sorted(Order.__optional_keys__))
print(get_type_hints(Order)["revenue"], Channel.__value__)
Output
none dict
['channel', 'order_id', 'revenue'] ['coupon']
<class 'float'> typing.Literal['online', 'store']
TypedDict need Write
every key required (default) class R(TypedDict): ...
one key may be absent key: NotRequired[T]
most keys optional class R(TypedDict, total=False): plus key: Required[T]
key present but may be null key: T | None
a read-only key (3.13+) key: ReadOnly[T]
a key that is not an identifier R = TypedDict("R", {"user-id": str})
import time
from collections.abc import Callable
from functools import wraps
type Metric = Callable[[list[float], list[float]], float]
def mae(y: list[float], p: list[float]) -> float:
return sum(abs(a - b) for a, b in zip(y, p, strict=True)) / len(y)
def timed[**P, R](func: Callable[P, R]) -> Callable[P, R]: # keeps the signature
@wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
print(f"{func.__name__} ran: {time.perf_counter() - start >= 0}")
return wrapper
@timed
def evaluate(y: list[float], p: list[float], metric: Metric = mae) -> float:
return round(metric(y, p), 3)
print(evaluate([3.0, 5.0], [2.5, 5.5]), timed.__type_params__)
Output
evaluate ran: True
0.5 (P, R)
Form Means
Callable[[int, str], bool] two positional parameters, returns bool
Callable[[], None] no parameters, returns nothing
Callable[..., R] any parameters
Callable[P, R] with [**P, R] the same parameters as the wrapped function
Callable[Concatenate[Request, P], R] one extra first parameter, then P
a Protocol with __call__ keyword names or overloads that Callable cannot express
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T: # T is bound per call
return items[0]
def largest[N: (int, float)](values: Sequence[N]) -> N: # constrained
return max(values)
class Stack[T]:
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
type Pair[T] = tuple[T, T] # a generic alias
s = Stack[str]()
s.push("P001")
print(first(("S01", "S02")), largest([3, 25, 1]), s.pop(), Pair.__type_params__)
Output
S01 25 P001 (T,)
from typing import Protocol, Self, overload, runtime_checkable
@runtime_checkable
class Model(Protocol):
def fit(self, X: list[list[float]], y: list[float]) -> Self: ...
def predict(self, X: list[list[float]]) -> list[float]: ...
class MeanModel: # no inheritance: matches by shape
def fit(self, X: list[list[float]], y: list[float]) -> Self:
self.mean_ = sum(y) / len(y)
return self
def predict(self, X: list[list[float]]) -> list[float]:
return [self.mean_] * len(X)
def score(model: Model, X: list[list[float]], y: list[float]) -> list[float]:
return model.fit(X, y).predict(X)
@overload
def to_f(c: float) -> float: ...
@overload
def to_f(c: list[float]) -> list[float]: ...
def to_f(c: float | list[float]) -> float | list[float]: # the real implementation
if isinstance(c, list):
return [round(x * 9 / 5 + 32, 1) for x in c]
return round(c * 9 / 5 + 32, 1)
print(score(MeanModel(), [[1.0], [2.0]], [10.0, 20.0]), isinstance(MeanModel(), Model))
print(to_f(21.5), to_f([19.0, 23.0]))
Output
[15.0, 15.0] True
70.7 [66.2, 73.4]
Protocol abc.ABC
matches by shape (structural) by inheritance (nominal)
third-party classes match without changes must inherit or be registered
shared code none can provide methods
runtime isinstance with @runtime_checkable; checks method names only yes

The full comparison, with collections.abc and registration, is on the ABC vs Protocol page.

import json
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, ClassVar, Final, TypedDict, cast
if TYPE_CHECKING: # False at runtime: the import costs nothing
from decimal import Decimal
class Config(TypedDict):
version: str
@dataclass
class Job:
name: str
count: ClassVar[int] = 0 # shared by the class, not a dataclass field
tags: list[str] = field(default_factory=list)
limit: Final[int] = 3 # a dataclass field that mypy will not let you reassign
def cost(self, rate: "Decimal") -> "Decimal": # quoted: not imported at runtime
return rate * self.limit
raw = json.loads('{"version": "1.4.0"}') # json gives Any
config = cast(Config, raw) # no check, no conversion: returns raw unchanged
print(config is raw, Job("load"), Job.count, TYPE_CHECKING)
Output
True Job(name='load', tags=[], limit=3) 0 False
Tool Effect for the checker Effect at runtime
cast(T, v) treats v as T returns v unchanged
TYPE_CHECKING True False
Final no reassignment, no override none
ClassVar[T] a class attribute; not a dataclass field dataclasses skip it
@overload several signatures only the last definition runs
@override error if the parent has no such method sets __override__
reveal_type(x) prints the inferred type prints the runtime type to stderr
assert_never(x) error if a case is reachable raises AssertionError
from __future__ import annotations none hints stay unevaluated strings (3.14 defers them by default)
Check Narrows x: str | int | None Note
if x is None: return str | int after the if the clearest form
isinstance(x, str) str inside works with tuples of types
if x: drops None, but also "" and 0 careful with numbers
match x: case str(): str in that case pattern matching narrows too
a TypeIs[str] function (3.13+) str when it returns True; also narrows the else branch your own reusable check
a TypeGuard[str] function str only when it returns True; no else narrowing the type may be unrelated to the input (list[object] → list[str])
assert x is not None not None after it for “cannot happen” cases

These commands run in a terminal, in an environment where mypy is installed (uv add --dev mypy).

Terminal
mypy script.py # check one file and what it imports
mypy src/ tests/ # check folders
mypy --strict src/ # every strict flag: hints required, no Any leaks
mypy --check-untyped-defs old.py # also check bodies of functions without hints
mypy --pretty --show-error-codes . # source line with markers, [code] at the end
mypy --python-version 3.12 src/ # check against an older Python
mypy --ignore-missing-imports src/ # quiet "missing stubs" for untyped libraries
mypy --install-types # install missing stub packages (types-requests)
dmypy run -- src/ # mypy daemon: fast re-checks
pyright src/ # Microsoft's checker, also inside VS Code Pylance
pyproject.toml
[tool.mypy]
python_version = "3.12"
strict = true # same as --strict on every run
warn_unreachable = true # code after return or impossible branches
pretty = true
files = ["src", "tests"] # what a bare `mypy` checks
[[tool.mypy.overrides]]
module = ["sklearn.*", "joblib.*"] # libraries without type hints
ignore_missing_imports = true
[[tool.mypy.overrides]]
module = ["tests.*"]
disallow_untyped_defs = false # relax rules for test files
Error code Meaning Typical fix
arg-type an argument has the wrong type convert it, or fix the hint
return-value the return value does not match -> return the right type or widen the hint
assignment a value does not fit the variable’s type
union-attr attribute access on X | None narrow with is None first
call-arg missing or unexpected argument
index wrong key type
typeddict-item unknown key or wrong value type in a TypedDict
var-annotated an empty container needs a hint xs: list[str] = []
no-untyped-def a function without hints (strict) add hints
no-any-return returns Any from a typed function (strict) cast or validate
import-untyped a library without type information install stubs (types-...) or an override
override a method’s signature breaks the parent’s match the parent’s parameters

A report line reads file.py:27: error: <message> [code]. The last line says Found N errors in M files or Success: no issues found in N source files.

Trap Symptom Fix
hints are not checked at runtime n: int = "3" runs without an error run mypy; validate untrusted data with pydantic
unannotated functions mypy says Success but checks nothing inside --strict or --check-untyped-defs
invariance list[int] rejected where list[float] is expected accept Sequence[float]
Optional[X] means “may be None” not “optional argument” write X | None; a default makes it optional
if x: as a None check 0, 0.0 and "" take the wrong branch if x is not None:
cast a wrong cast hides a real bug validate first, then cast
json.load returns Any no errors for any key or type a TypedDict plus validation
a bare # type: ignore hides every future error on that line # type: ignore[code]
a list[T] = [] default the shared mutable default bug x: list[T] | None = None
get_args(Alias) on a type alias returns () get_args(Alias.__value__)
isinstance with a protocol checks only that method names exist real checks in the method
bool is a subtype of int True passes as int test isinstance(x, bool) first
PEP 695 syntax on Python 3.11 or older SyntaxError use TypeVar and Generic there
forward reference to a later class NameError at import on 3.12/3.13 quote it ("Node") or from __future__ import annotations
untyped libraries import-untyped; values become Any an override in pyproject.toml, or stub packages

pytest finds functions named test_*, runs them and reports every failed assert with the values involved. This page is a reference for writing and running tests in any Python project: libraries, web back ends, scripts and data pipelines.

I want to… Use… Example
run every test pytest pytest -q
run one file, class or test a node ID pytest tests/test_prices.py::test_parse
run tests whose name matches -k EXPR pytest -k "parse and not slow"
run tests with a marker -m EXPR pytest -m "not slow"
stop at the first failure -x pytest -x
rerun only the failures --lf (--ff: failures first) pytest --lf
see one line per test -v pytest -v
see print() output -s pytest -s -k report
list tests without running them --collect-only -q pytest --co -q
find slow tests --durations=N pytest --durations=5
debug a failure --pdb pytest -x --pdb
check a value plain assert assert total == 304.09
compare floats pytest.approx assert mean == pytest.approx(0.3)
check that code raises pytest.raises(E, match=...) with pytest.raises(ValueError, match="price"):
check that code warns pytest.warns(W, match=...) with pytest.warns(DeprecationWarning):
share setup between tests a fixture @pytest.fixture def orders(): ...
clean up after a test a yield fixture conn = connect(); yield conn; conn.close()
share fixtures across files conftest.py tests/conftest.py
build expensive data once a wider scope @pytest.fixture(scope="session")
a temporary folder tmp_path path = tmp_path / "out.csv"
set an environment variable monkeypatch.setenv monkeypatch.setenv("API_KEY", "test")
replace a function or attribute monkeypatch.setattr monkeypatch.setattr(app, "fetch", fake)
capture print() output capsys capsys.readouterr().out
capture log records caplog assert "dropped" in caplog.text
run one test on many inputs @pytest.mark.parametrize @pytest.mark.parametrize("raw", ["$1", "1"])
name parametrized cases pytest.param(..., id=...) or ids= pytest.param("", None, id="empty")
skip a test skip, skipif, importorskip @pytest.mark.skipif(sys.platform == "win32", reason="posix")
mark a known bug xfail(strict=True) @pytest.mark.xfail(reason="bug 42", strict=True)
a fake object with recorded calls unittest.mock.Mock fake.assert_called_once_with("P001")
measure coverage pytest-cov pytest --cov=mypkg --cov-report=term-missing
fail CI below a coverage level --cov-fail-under pytest --cov=mypkg --cov-fail-under=90
compare DataFrames pd.testing.assert_frame_equal assert_frame_equal(got, expected)
run the examples in docstrings --doctest-modules pytest --doctest-modules src/
test async def functions a plugin marker: pytest-asyncio or anyio @pytest.mark.asyncio / @pytest.mark.anyio
test a rule on many generated inputs property-based testing (plugin: hypothesis) @given(st.floats(min_value=0))
src layout with tests
project/
├── pyproject.toml # [tool.pytest] settings
├── src/
│ └── shop/
│ ├── __init__.py
│ └── prices.py
└── tests/
├── conftest.py # fixtures for every test below this folder
├── test_prices.py # one test file per module
└── integration/
├── conftest.py # extra fixtures for this subfolder only
└── test_api.py
pytest collects Rule Config key
files test_*.py or *_test.py python_files
functions names starting with test python_functions
classes Test* classes without __init__ python_classes
methods test* methods inside a Test* class python_functions
folders the arguments, or testpaths, recursively testpaths
Rule Why
tests import your package by name (from shop.prices import parse) they test what users import
install the project editable (uv sync) or set pythonpath = ["src"] so the import works
unique test file names, or __init__.py in test folders avoids “import file mismatch” errors
one behavior per test, named after the rule test_parse_rejects_negative_price
arrange, act, assert set up, call once, check
build data paths from Path(__file__).parent tests pass from any working folder
Terminal
cat > test_demo.py <<'EOF'
import pytest
def parse_price(text: str) -> float | None:
cleaned = text.strip().removeprefix("$").replace(",", "")
if cleaned in {"", "N/A", "-"}:
return None
return float(cleaned)
@pytest.fixture
def raw_prices() -> list[str]:
return ["$79.99", "$1,299.00", "N/A"]
def test_parses_a_list(raw_prices):
assert [parse_price(p) for p in raw_prices] == [79.99, 1299.0, None]
@pytest.mark.parametrize(
("text", "expected"),
[("$79.99", 79.99), (" 14.99 ", 14.99), pytest.param("", None, id="empty")],
)
def test_parse_price(text, expected):
assert parse_price(text) == expected
def test_garbage_raises():
with pytest.raises(ValueError, match="could not convert"):
parse_price("$12.x0")
def test_writes_file(tmp_path):
out = tmp_path / "prices.txt"
out.write_text("79.99\n", encoding="utf-8")
assert out.read_text(encoding="utf-8").strip() == "79.99"
EOF
pytest -v --no-header test_demo.py
Output
======================================= test session starts ========================================
collecting ... collected 6 items
test_demo.py::test_parses_a_list PASSED [ 16%]
test_demo.py::test_parse_price[$79.99-79.99] PASSED [ 33%]
test_demo.py::test_parse_price[ 14.99 -14.99] PASSED [ 50%]
test_demo.py::test_parse_price[empty] PASSED [ 66%]
test_demo.py::test_garbage_raises PASSED [ 83%]
test_demo.py::test_writes_file PASSED [100%]
======================================== 6 passed in 0.01s =========================================

The IDs in brackets come from the parameter values: $79.99-79.99 joins the two arguments with -, and empty is the id of the pytest.param.

Check Write Note
equality assert got == expected pytest shows both values and a diff
None assert value is None is, not ==
truthiness assert result, assert not errors
membership assert "P001" in ids
subset assert {"a", "b"} <= set(keys)
type assert isinstance(x, float)
float assert x == pytest.approx(0.3) never == on computed floats
an exception with pytest.raises(KeyError): only the failing call inside
a message assert ok, f"bad row: {row}" the message shows on failure
sorted output assert sorted(got) == sorted(expected) when order does not matter
a DataFrame pd.testing.assert_frame_equal(got, expected) assert df1 == df2 raises ValueError
a NumPy array np.testing.assert_allclose(got, expected)
import warnings
import pytest
print(0.1 + 0.2 == pytest.approx(0.3)) # default rel=1e-6
print([0.1 + 0.2, 1.0] == pytest.approx([0.3, 1.0])) # lists, tuples, dicts
print(1e-9 == pytest.approx(0.0), 1e-9 == pytest.approx(0.0, abs=1e-6))
print(1213 == pytest.approx(1200, rel=0.02)) # 2% tolerance
with pytest.raises(ValueError, match=r"out of range: 1\.5") as excinfo:
raise ValueError("discount out of range: 1.5")
print(excinfo.type.__name__, excinfo.value.args)
with pytest.warns(DeprecationWarning, match="old_api"):
warnings.warn("old_api() is deprecated", DeprecationWarning, stacklevel=1)
print("warning seen")
Output
True
True
False True
True
ValueError ('discount out of range: 1.5',)
warning seen
Tool Argument Meaning
pytest.approx(x) rel=1e-6 relative tolerance
abs=1e-12 absolute tolerance; set it near 0
nan_ok=True treat nan == nan as equal
pytest.raises(E) match=r"..." re.search on str(exception)
a tuple of types any of them
as excinfo .value, .type, .traceback
pytest.raises(SystemExit) excinfo.value.code test a CLI’s exit code
pytest.warns(W, match=...) as record the list of warnings
pytest.fail("msg"), pytest.skip("msg") inside a test fail or skip from code
tests/conftest.py
import sqlite3
from collections.abc import Iterator
import pytest
@pytest.fixture
def order() -> dict[str, object]: # function scope: a fresh dict per test
return {"order_id": "O000001", "quantity": 1, "unit_price": 69.99}
@pytest.fixture(scope="session") # built once per pytest run
def products() -> list[str]:
return ["P001", "P002", "P003"]
@pytest.fixture
def db() -> Iterator[sqlite3.Connection]: # setup, yield, teardown
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE orders (id TEXT, qty INTEGER)")
yield conn # the test runs here
conn.close() # runs even when the test fails
@pytest.fixture
def make_order(order): # a factory fixture uses another fixture
def _make(**changes):
return order | changes
return _make
@pytest.fixture(params=["sqlite", "duckdb"]) # every test using it runs twice
def backend(request) -> str:
return request.param
@pytest.fixture(autouse=True) # applies to every test without naming it
def fixed_env(monkeypatch):
monkeypatch.setenv("APP_ENV", "test")
Scope Created once per Use for
function (default) test anything a test may change
class test class shared setup for a group
module test file a loaded dataset read by many tests
package test folder (package)
session whole run a database server, a large read-only fixture
Fact Detail
request a fixture name it as a test parameter: def test_total(order):
conftest.py fixtures there are visible in its folder and below; no import needed
teardown code after yield runs after the test, pass or fail
a wider scope cannot use a narrower one a session fixture cannot use tmp_path; use tmp_path_factory
list fixtures and where they live pytest --fixtures
watch setup and teardown pytest --setup-show
Fixture Gives Example
tmp_path a new empty pathlib.Path per test (tmp_path / "a.csv").write_text("x")
tmp_path_factory session-wide temp folders tmp_path_factory.mktemp("data")
monkeypatch temporary changes, undone after the test see the table below
capsys captured sys.stdout and sys.stderr out, err = capsys.readouterr()
capfd capture at the file-descriptor level output of subprocesses and C code
caplog captured log records caplog.set_level("INFO"); caplog.records
recwarn recorded warnings len(recwarn)
request the running test; request.param parametrized fixtures
monkeypatch. Does
setenv("K", "v"), delenv("K", raising=False) change environment variables
setattr(module, "name", value) replace a function, constant or method
setattr("pkg.module.name", value) the same, by dotted path
setitem(d, "k", v), delitem(d, "k") change a dict, such as a settings dict
chdir(tmp_path) change the working folder
syspath_prepend(path) add an import path
tests/test_report.py
import logging
import shop.report as report
def test_summary_prints(capsys):
report.print_summary({"rows": 1200})
assert capsys.readouterr().out == "rows: 1,200\n"
def test_uses_fake_fetch(monkeypatch):
monkeypatch.setattr(report, "fetch", lambda url: {"status": "ok"}) # no network
assert report.health() == "ok"
def test_logs_drops(caplog):
with caplog.at_level(logging.WARNING):
report.clean([{"qty": -1}])
assert "dropped 1 row" in caplog.text
tests/test_dates.py
from datetime import date
import pytest
from shop.dates import parse_date
JAN_7 = date(2023, 1, 7)
@pytest.mark.parametrize(
("text", "expected"), # tuple of names, or "text,expected"
[
("2023-01-07", JAN_7),
pytest.param("07/01/2023", JAN_7, id="day-first"),
pytest.param("1/7/2023", JAN_7, id="us", marks=pytest.mark.xfail(strict=True)),
],
)
def test_parse_date(text, expected):
assert parse_date(text) == expected
@pytest.mark.parametrize("field", ["region", "channel"])
@pytest.mark.parametrize("token", ["", "N/A"], ids=["empty", "na"])
def test_missing(field, token): ... # stacked: 2 x 2 = 4 tests
Value Automatic ID part
str, int, float, bool, None the value: north, 79.99, None
other objects (date, dict) argument name and index: expected0
several arguments joined with -: $79.99-79.99
ids=[...], ids=func, pytest.param(id=...) your names

Select one case from the terminal with its ID, in quotes: pytest "tests/test_dates.py::test_parse_date[day-first]".

Mark Effect
@pytest.mark.skip(reason="...") never run
@pytest.mark.skipif(cond, reason="...") skip when cond is true
pytest.importorskip("polars") skip the module when a package is missing
@pytest.mark.xfail(reason="...", strict=True) expected to fail; a pass becomes a failure
@pytest.mark.parametrize(...) many cases
@pytest.mark.usefixtures("db") use a fixture without a parameter
@pytest.mark.filterwarnings("error") turn warnings into errors for one test
@pytest.mark.slow (your own) select with -m slow or -m "not slow"; register it in the config
pytestmark = pytest.mark.slow at module level: marks every test in the file
Flag Does
-q / -v / -vv quieter / one line per test / full diffs
-x, --maxfail=N stop after the first or the N-th failure
-k "expr" select by name: and, or, not, substrings
-m "expr" select by marker
--lf, --ff last failed only / failed first
--sw stepwise: stop at a failure, start there next time
-s no output capture: see print()
--tb=short, line, no, long traceback style
-l show local variables in tracebacks
-r fEsxX a short summary of failures, errors, skips, xfails
--co -q list the collected tests
--durations=N the N slowest setup, call and teardown phases
--setup-show show fixture setup and teardown
--pdb, --trace debugger on failure / at the start of each test
-p no:cacheprovider do not write .pytest_cache
-W error turn warnings into errors
-n auto run in parallel (plugin: pytest-xdist)
--cov=pkg, --cov-report=term-missing, --cov-branch coverage (plugin: pytest-cov)
--cov-fail-under=90 fail below 90% coverage
Exit code Meaning
0 all collected tests passed
1 some tests failed
2 interrupted, or an error during collection
3 internal error
4 usage error (a bad option)
5 no tests collected
pyproject.toml
[dependency-groups]
dev = ["pytest>=9.2", "pytest-cov>=7.1"]
[tool.pytest] # pytest 9: native TOML types
testpaths = ["tests"]
pythonpath = ["src"] # import the package without installing it
addopts = ["-q", "--tb=short"]
strict = true # unknown markers and config keys become errors
markers = ["slow: reads the full data files"]
filterwarnings = ["error"] # every warning fails a test
[tool.coverage.run]
branch = true
source = ["shop"]
[tool.coverage.report]
show_missing = true
fail_under = 90
exclude_also = ['if __name__ == "__main__":', "if TYPE_CHECKING:"]

Older projects use [tool.pytest.ini_options], pytest.ini or setup.cfg. Use one place only.

import os
from unittest.mock import Mock, patch
fetch = Mock(return_value={"status": 200, "items": ["P001"]})
print(fetch("https://api.example.com/products")["items"])
fetch.assert_called_once_with("https://api.example.com/products")
print(fetch.call_count)
flaky = Mock(side_effect=[TimeoutError("slow"), {"status": 200}]) # one value per call
try:
flaky()
except TimeoutError as err:
print("first call:", err, "| second call:", flaky()["status"])
with patch("os.cpu_count", return_value=2): # patch where the name is looked up
print(os.cpu_count()) # restored after the block
Output
['P001']
1
first call: slow | second call: 200
2
Tool Use
Mock(return_value=v) a fake function that returns v
Mock(side_effect=Exc) / side_effect=[...] raise, or return a different value per call
m.assert_called_once_with(...), m.call_args, m.call_count check the calls
patch("pkg.mod.name") replace a name for a with block or a test
patch.object(obj, "attr") replace an attribute of one object
Mock(spec=RealClass) / create_autospec(func) reject attributes or signatures the real object lacks
monkeypatch.setattr the pytest way; simpler for plain replacements
Terminal
pytest --cov=shop --cov-branch --cov-report=term-missing # table after the tests
pytest --cov=shop --cov-report=html # htmlcov/index.html
pytest --cov=shop --cov-fail-under=90 # non-zero exit below 90%
coverage report -m # table from the .coverage file
Column Meaning
Stmts / Miss statements / statements that no test ran
Branch / BrPart branch directions / branches taken only one way
Cover percentage
Missing line numbers, and partial branches such as 7->9

Exclude a line with # pragma: no cover. High coverage means every line ran once, not that the results are right.

Trap Symptom Fix
a file or function without the test prefix no tests ran, exit code 5 name it test_*.py and def test_*
two test files with the same name in different folders import file mismatch unique names, or __init__.py in test folders
ModuleNotFoundError for your package tests cannot import src/ code editable install, pythonpath = ["src"] or python -m pytest
assert df1 == df2 ValueError: The truth value of a DataFrame is ambiguous pd.testing.assert_frame_equal
== on computed floats random-looking failures pytest.approx
pytest.approx(0.0) tiny differences fail pass abs= near zero
pytest.raises(ValueError) without match passes for the wrong ValueError add match=
several lines inside pytest.raises lines after the raising line never run only the failing call inside
a shared mutable fixture in a wide scope tests pass alone, fail together function scope, or return copies
patching module.name after from module import name the code still uses the original patch where the name is looked up
capsys.readouterr() called twice the second call is empty call it once and keep the result
a typo in a marker name a warning, the test runs anyway strict = true in the config
a test that never failed it may test nothing break the code once and watch it fail
flaky tests pass and fail at random fix seeds, time, order and shared state; do not just rerun
node IDs with brackets in the shell no matches found (zsh) quote the node ID

Fast Python comes from three habits: measure first, pick the right data structure, and use concurrency only for the kind of work it helps. This page gives the costs, the measuring tools and copy-ready templates for thread pools, process pools and asyncio.

I want to… Use… Example
time one run of a slow step time.perf_counter() start = perf_counter() … perf_counter() - start
benchmark a small snippet timeit.timeit(func, number=n) timeit(lambda: sum(xs), number=100) / 100
benchmark with less noise min(timeit.repeat(...)) the minimum, not the mean
benchmark from a terminal python -m timeit python -m timeit -s "xs = list(range(1000))" "sum(xs)"
find the slow function python -m cProfile -s cumulative script.py or with cProfile.Profile() as p:
measure memory tracemalloc tracemalloc.get_traced_memory()
test membership many times a set if pid in valid_ids:
look up records by key a dict index built once by_id = {r["id"]: r for r in rows}
a FIFO queue collections.deque q.append(x); q.popleft()
count values collections.Counter Counter(levels)
the top k items heapq.nlargest(k, xs) nlargest(10, orders, key=...)
search a sorted list bisect.bisect_left O(log⁡n)O(\log n)
avoid recomputation functools.cache @cache on a pure function
build a long string "".join(parts) not s += part in a loop
fast numeric loops NumPy vector operations (prices * qty).sum()
stream a big file a generator sum(1 for line in f if "ERROR" in line)
speed up many waits (network, disk) ThreadPoolExecutor pool.map(fetch, urls)
speed up pure Python computing ProcessPoolExecutor pool.map(simulate, seeds)
thousands of concurrent connections asyncio await asyncio.gather(*tasks)
results in input order pool.map / asyncio.gather
results as they finish as_completed for fut in as_completed(futures):
limit concurrency asyncio.Semaphore(n), max_workers=n async with sem:
a time limit asyncio.timeout(s), future.result(timeout=s) async with asyncio.timeout(5):
run blocking code from async code asyncio.to_thread await asyncio.to_thread(requests.get, url)
cancel the rest when one task fails asyncio.TaskGroup async with asyncio.TaskGroup() as tg:
share data between threads safely threading.Lock, queue.Queue with lock: total += x
check whether the GIL is on sys._is_gil_enabled() Python 3.13+
Operation Cost Note
lst[i], lst[i] = x, len(lst) O(1)O(1)
lst.append(x), lst.pop() O(1)O(1) amortized at the end
lst.insert(0, x), lst.pop(0) O(n)O(n) shifts every item: use deque
x in lst, lst.index(x), lst.count(x), lst.remove(x) O(n)O(n) a scan
lst[a:b], lst.copy(), lst + other O(k)O(k) / O(n)O(n) copies
lst.sort(), sorted(xs) O(nlog⁡n)O(n \log n) stable
min, max, sum, any, all O(n)O(n) one pass
d[k], d[k] = v, k in d, del d[k], d.get(k) O(1)O(1) average hashing
set.add, x in s, s.discard(x) O(1)O(1) average
a | b / a & b (sets of sizes n and m) O(n+m)O(n + m) / O(min⁡(n,m))O(\min(n, m))
deque.append, appendleft, pop, popleft O(1)O(1) both ends
deque[i] in the middle O(n)O(n)
heapq.heappush, heappop O(log⁡n)O(\log n)
heapq.nlargest(k, xs) O(nlog⁡k)O(n \log k)
bisect.bisect_left O(log⁡n)O(\log n) on a sorted list
bisect.insort O(n)O(n) the insert shifts items
s + t (strings), s.replace, x in s O(n)O(n) strings are immutable
"".join(parts) O(total length)O(\text{total length}) one copy
s += piece in a loop up to O(n2)O(n^2) many copies
n O(log⁡n)O(\log n) O(n)O(n) O(nlog⁡n)O(n \log n) O(n2)O(n^2)
1,000 10 1,000 10,000 1,000,000
1,000,000 20 1,000,000 20,000,000 101210^{12}

A rough guide: pure Python does about 10710^7 simple steps per second. O(n2)O(n^2) on a million items never finishes.

import timeit
ids = [f"C{i:05d}" for i in range(5_000)]
as_list, as_set = ids, set(ids)
probe = "C04999" # the worst case for a list: the last item
t_list = min(timeit.repeat(lambda: probe in as_list, number=200, repeat=3))
t_set = min(timeit.repeat(lambda: probe in as_set, number=200, repeat=3))
print(t_set < t_list, t_list / t_set > 10) # print comparisons, not raw timings
Output
True True
import cProfile
import pstats
def parse(lines: list[str]) -> list[float]:
return [float(x) for x in lines]
def pipeline() -> float:
return sum(sum(parse(["21.5", "22.0", "19.8"])) for _ in range(100))
with cProfile.Profile() as profiler:
pipeline()
stats = pstats.Stats(profiler).strip_dirs().sort_stats(pstats.SortKey.CUMULATIVE)
funcs = stats.get_stats_profile().func_profiles # name -> FunctionProfile
print(funcs["pipeline"].ncalls, funcs["parse"].ncalls) # call counts are exact
Output
1 100
import tracemalloc
tracemalloc.start()
squares_list = [n * n for n in range(100_000)] # stores every item
_, peak_list = tracemalloc.get_traced_memory()
del squares_list
tracemalloc.reset_peak() # start a new peak measurement
total = sum(n * n for n in range(100_000)) # a generator: one item at a time
_, peak_gen = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(total, peak_gen < peak_list / 10)
Output
333328333350000 True
Terminal
python -m timeit -s "xs = list(range(10**5))" "sum(xs)" # -n loops, -r repeats
python -m cProfile -s cumulative report.py | head -25 # sorted profile
python -m cProfile -o report.prof report.py # save, then:
python -m pstats report.prof # interactive: sort, stats 10
python -X importtime -c "import pandas" 2> imports.txt # slow imports
Profile column Meaning
ncalls number of calls (3/1: 3 calls, 1 not recursive)
tottime time in the function itself
cumtime time in the function and everything it calls
percall tottime / ncalls, then cumtime / ncalls

Other tools: py-spy (a sampling profiler that attaches to a running process), line_profiler (time per line), scalene (CPU and memory), memray (memory).

Need Slow Fast Why
many membership tests x in a_list x in a_set O(n)O(n) → O(1)O(1)
join two record lists nested loops a dict index on one side O(n⋅m)O(n \cdot m) → O(n+m)O(n + m)
a queue lst.pop(0) deque.popleft() O(n)O(n) → O(1)O(1)
counts lst.count(x) per value Counter(lst) one pass
top k sorted(xs)[:k] heapq.nsmallest(k, xs) no full sort
a sorted list kept up to date append and sort each time bisect.insort no re-sort
the same slow call again recompute @cache a dict lookup
big text s += part "".join(parts) one copy
numeric arrays a Python loop NumPy / pandas vector operations (NumPy ufuncs) the loop runs in C
many small objects a dict per object @dataclass(slots=True) or tuples less memory
a huge file f.readlines() for line in f: constant memory
from collections import Counter
orders = [("O1", "C01", 79.99), ("O2", "C02", 14.99), ("O3", "C01", 249.0)]
customers = [("C01", "North"), ("C02", "West")]
region_of = dict(customers) # an index: built once in O(m)
revenue = Counter()
for _, customer_id, amount in orders: # O(n) lookups, no inner loop
revenue[region_of[customer_id]] += amount
print(dict(revenue))
Output
{'North': 328.99, 'West': 14.99}
threading / ThreadPoolExecutor multiprocessing / ProcessPoolExecutor asyncio
speeds up I/O-bound work: network, disk, sleeps CPU-bound pure Python many I/O tasks at once
runs Python in parallel no (GIL), yes on the free-threaded build yes no: one thread
memory shared separate; arguments are pickled shared
start cost small large tiny
typical count 4–32 about one per core thousands of tasks
switches tasks at any bytecode the OS only at await
main risk race conditions on shared data main guard, pickling, copying big data one blocking call stalls everything
libraries any (requests, database drivers) any picklable function async ones (httpx.AsyncClient, asyncpg)
Situation Choose
download 50 files or call an API 200 times threads, or asyncio with an async client
parse 1,000 files with pure Python processes
NumPy, pandas, scikit-learn heavy math vectorize first (NumPy); often already parallel inside C; try n_jobs=-1 before a pool
a web server with many idle connections asyncio (FastAPI, aiohttp)
a blocking library inside async code asyncio.to_thread
CPU work and you have the free-threaded build threads (check that your libraries support it)

The global interpreter lock (GIL) is a lock inside standard CPython that lets only one thread run Python bytecode at a time. Threads still help with I/O, because a thread that waits for the network, the disk or time.sleep releases the GIL, and many C libraries (NumPy, hashlib, zlib) release it during long computations. Pure Python computation in threads does not get faster. Each process has its own interpreter and its own GIL, so process pools run Python code in parallel at the price of pickling data between processes.

Python 3.13 added an optional free-threaded build without a GIL (the python3.13t executable). Python 3.14 made it officially supported, but it is still a separate download, not the default. On it, threads run Python code on several cores at once. Single-threaded code runs a little slower, and every C extension must declare support; otherwise the GIL turns back on when that extension loads. Check with sys._is_gil_enabled() (3.13+) and sysconfig.get_config_var("Py_GIL_DISABLED"). Python 3.14 also adds concurrent.futures.InterpreterPoolExecutor: several interpreters in one process, each with its own GIL.

import queue
import threading
total = 0
lock = threading.Lock()
def add_many(n: int) -> None:
global total
for _ in range(n):
with lock: # one thread at a time in this block
total += 1
threads = [threading.Thread(target=add_many, args=(10_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(total) # always 40000 with the lock
tasks: queue.Queue[str | None] = queue.Queue()
results: queue.Queue[str] = queue.Queue() # thread-safe without a lock
def worker() -> None:
while (item := tasks.get()) is not None: # None is the stop signal
results.put(item.upper())
workers = [threading.Thread(target=worker) for _ in range(2)]
for w in workers:
w.start()
for item in ["s01", "s02", "s03"]:
tasks.put(item)
for _ in workers:
tasks.put(None) # one sentinel per worker
for w in workers:
w.join()
print(sorted(results.get() for _ in range(results.qsize())))
Output
40000
['S01', 'S02', 'S03']
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch(page: int) -> str:
time.sleep(0.02 * (4 - page)) # stands for a network call
if page == 3:
raise TimeoutError(f"page {page} timed out")
return f"page {page}: ok"
with ThreadPoolExecutor(max_workers=4) as pool: # 1) map: input order
print(list(pool.map(fetch, [1, 2])))
results, errors = {}, {}
with ThreadPoolExecutor(max_workers=4) as pool: # 2) submit: errors per task
futures = {pool.submit(fetch, p): p for p in [1, 2, 3, 4]}
for future in as_completed(futures): # finish order
page = futures[future]
try:
results[page] = future.result(timeout=5) # re-raises the task's error
except TimeoutError as err:
errors[page] = str(err)
print(sorted(results), errors)
Output
['page 1: ok', 'page 2: ok']
[1, 2, 4] {3: 'page 3 timed out'}
cpu_pool.py (run as a file)
import multiprocessing
from concurrent.futures import ProcessPoolExecutor
def simulate(seed: int) -> float: # top level: workers import it by name
import random
rng = random.Random(seed) # a seed per task: same result in any process
return sum(rng.random() for _ in range(1_000_000)) / 1_000_000
def main() -> None:
ctx = multiprocessing.get_context("spawn") # same behavior on every OS
with ProcessPoolExecutor(max_workers=4, mp_context=ctx) as pool:
means = list(pool.map(simulate, range(8), chunksize=2))
print(round(sum(means) / len(means), 3))
if __name__ == "__main__": # required: each worker imports this file
main()
API Does
ThreadPoolExecutor(max_workers=n) default min(32, cpu_count + 4) threads
ProcessPoolExecutor(max_workers=n, mp_context=ctx) default: one process per CPU
pool.map(func, items, timeout=None, chunksize=1) results in input order; the first error is raised while you iterate
pool.submit(func, *args, **kwargs) one task, returns a Future
future.result(timeout=s) the value, or the task’s exception
as_completed(futures, timeout=s) futures in finish order
wait(futures, return_when=FIRST_COMPLETED) (done, not_done) sets
pool.shutdown(cancel_futures=True) stop and drop queued tasks
import asyncio
async def fetch(day: str, delay: float, sem: asyncio.Semaphore) -> str:
async with sem: # at most 2 at a time
await asyncio.sleep(delay) # never time.sleep() in a coroutine
return f"{day}: ok"
async def main() -> None:
sem = asyncio.Semaphore(2) # create inside the running loop
days = ["2024-05-01", "2024-05-02", "2024-05-03"]
print(await asyncio.gather(*(fetch(d, 0.02, sem) for d in days))) # input order
results = await asyncio.gather( # errors as values instead of raising
fetch("ok", 0.01, sem), asyncio.wait_for(asyncio.sleep(1), timeout=0.01),
return_exceptions=True,
)
print([type(r).__name__ for r in results])
try:
async with asyncio.timeout(0.02): # a deadline for the whole block
await asyncio.sleep(1)
except TimeoutError:
print("timed out")
async with asyncio.TaskGroup() as tg: # waits for all; cancels on a failure
tasks = [tg.create_task(fetch(d, 0.01, sem)) for d in days[:2]]
print([t.result() for t in tasks])
total = await asyncio.to_thread(sum, range(1_000)) # blocking code in a thread
print(total)
asyncio.run(main()) # one entry point per program
Output
['2024-05-01: ok', '2024-05-02: ok', '2024-05-03: ok']
['str', 'TimeoutError']
timed out
['2024-05-01: ok', '2024-05-02: ok']
499500
import asyncio
async def producer(queue: asyncio.Queue[int]) -> None:
for n in range(5):
await queue.put(n)
async def consumer(queue: asyncio.Queue[int], out: list[int]) -> None:
while True:
n = await queue.get()
out.append(n * n)
queue.task_done()
async def pipeline() -> list[int]:
queue: asyncio.Queue[int] = asyncio.Queue(maxsize=2) # back-pressure
out: list[int] = []
workers = [asyncio.create_task(consumer(queue, out)) for _ in range(2)]
await producer(queue)
await queue.join() # wait until every item is processed
for w in workers:
w.cancel()
return sorted(out)
print(asyncio.run(pipeline()))
Output
[0, 1, 4, 9, 16]
API Does
async def f() f() returns a coroutine; nothing runs until it is awaited
await x pause this coroutine until x finishes
asyncio.run(main()) start a loop, run main, close the loop
asyncio.gather(*aws, return_exceptions=False) run together; results in argument order
asyncio.TaskGroup() structured tasks; cancels siblings on an error (3.11+)
asyncio.create_task(coro) start now; keep a reference
asyncio.Semaphore(n) a concurrency limit
asyncio.timeout(s), asyncio.wait_for(aw, s) deadlines; raise TimeoutError
asyncio.as_completed(aws) results in finish order
asyncio.to_thread(func, *args) run a blocking call in a thread
asyncio.Queue(maxsize=n) producer and consumer tasks
asyncio.sleep(s) a non-blocking wait

In Jupyter the loop is already running: write await main(), not asyncio.run(main()).

Trap Symptom Fix
optimizing without measuring effort spent on the wrong code profile first, then time the fix
one timing of fast code noise larger than the effect timeit with number=, the minimum of repeat
x in big_list inside a loop quadratic time build a set or dict once, outside the loop
s += piece in a loop slow on long strings "".join(parts)
threads for CPU-bound Python no speed-up, sometimes slower processes (or NumPy, or the free-threaded build)
shared counters in threads lost updates, wrong totals a Lock, or return results instead of sharing
a process pool without the main guard RuntimeError about the bootstrapping phase if __name__ == "__main__":
a lambda or nested function in a process pool PicklingError or AttributeError: Can't pickle local object a top-level function
many tiny tasks in a process pool slower than a plain loop few, large chunks; chunksize=
big arguments to processes time goes to pickling pass file paths or indexes, not data
as_completed order output order changes between runs sort, or use map
a coroutine called without await it never runs; RuntimeWarning: coroutine ... was never awaited await it or wrap it in a task
time.sleep or requests.get in a coroutine every task stalls asyncio.sleep, an async client or to_thread
a task without a reference it can be garbage collected mid-run keep the task, or use a TaskGroup
unlimited gather against a real API HTTP 429 rate limits, bans a Semaphore
asyncio.run inside Jupyter RuntimeError: asyncio.run() cannot be called from a running event loop await main()
a module-level asyncio.Semaphore or Queue errors when asyncio.run is called twice create them inside main()
assuming the free-threaded build is installed no speed-up from threads check sys._is_gil_enabled()

Every Python project needs the same few tools: an environment, a dependency manager, a linter and formatter, a type checker and a test runner. This page covers uv, venv and pip, pyproject.toml, ruff, mypy and pre-commit, and how a package is laid out. Most commands change your environment or need the network, so they are shown, not run.

I want to… Use… Example
start a new project uv init uv init --package shop (src layout)
install a Python version uv python install uv python install 3.13
pin the project’s Python uv python pin writes .python-version
create an environment uv venv / python -m venv .venv uv venv --python 3.13
activate it source .venv/bin/activate Windows: .venv\Scripts\activate
add a dependency uv add uv add "pandas>=3.1"
add a developer tool uv add --dev uv add --dev pytest ruff mypy
remove a dependency uv remove uv remove requests
lock exact versions uv lock writes uv.lock
upgrade one locked package uv lock --upgrade-package uv lock --upgrade-package pandas
make .venv match the lock uv sync uv sync --locked in CI
run a command in the project uv run uv run pytest -q
run a tool without installing it uvx uvx ruff check .
install a CLI tool globally uv tool install uv tool install pre-commit
a one-file script with its own dependencies uv add --script uv run report.py reads the inline metadata
pip-style install uv pip install / python -m pip install uv pip install -r requirements.txt
install my project for development an editable install uv pip install -e .
pin everything to a requirements file uv pip compile / uv export uv export -o requirements.txt
see what is installed uv pip list, uv tree uv tree --depth 1
lint ruff check ruff check --fix .
format ruff format ruff format --check . in CI
sort imports ruff check --select I --fix
explain a lint rule ruff rule CODE ruff rule B006
type check mypy mypy --strict src/
run checks before every commit pre-commit pre-commit install
build a wheel uv build writes dist/*.whl and dist/*.tar.gz
bump the version uv version --bump uv version --bump minor
run a module as a script python -m python -m shop data/sales.csv
add a command-line command [project.scripts] shop = "shop.cli:main"
read a package’s version in code importlib.metadata.version version("pandas")
check that a venv is active sys.prefix != sys.base_prefix True inside .venv

uv is a fast, all-in-one project manager: it installs Python, creates .venv, resolves and locks dependencies and runs tools.

Command Does
uv init [--package] [name] new project: pyproject.toml, .python-version, README.md; --package uses the src layout
uv add pkg, uv add --dev pkg, uv add --group docs pkg add to dependencies / the dev group / another group; then lock and sync
uv add --optional plots matplotlib add an extra: pip install "shop[plots]"
uv remove pkg remove a dependency
uv lock resolve all platforms; write uv.lock
uv lock --upgrade / --upgrade-package pkg allow newer versions in the lock
uv sync install exactly what uv.lock says, remove the rest
uv sync --locked fail if uv.lock is out of date (CI)
uv sync --frozen, --no-dev, --all-groups use the lock as is / skip dev tools / every group
uv run cmd sync, then run cmd inside .venv (no activation needed)
uv run --with rich script.py run with an extra package, just this once
uv tree the dependency tree
uv export --format requirements-txt -o requirements.txt the lock as a pinned requirements file
uv build / uv publish build a wheel and an sdist / upload to PyPI
uv python install 3.13, uv python list, uv python pin 3.13 manage interpreters
uv tool install ruff, uvx ruff global CLI tools / a temporary run
uv venv [--python 3.13] create .venv
uv pip install, uv pip sync, uv pip compile, uv pip freeze the pip-compatible interface
uv cache clean free disk space
report.py (a script with inline metadata)
# /// script
# requires-python = ">=3.12"
# dependencies = ["httpx>=0.28"]
# ///
import httpx # `uv run report.py` installs httpx in a cached environment
print(httpx.__version__)
Terminal
python -m venv .venv # create (standard library)
source .venv/bin/activate # macOS / Linux
.venv\Scripts\activate # Windows (PowerShell or cmd)
python -m pip install --upgrade pip # pip of this exact interpreter
python -m pip install "pandas>=3.1,<4" # install with a range
python -m pip install -r requirements.txt # install a list
python -m pip install -e ".[dev]" # editable install plus the dev extra
python -m pip freeze > requirements.txt # dump exact versions
python -m pip list --outdated # what could be upgraded
python -m pip show pandas # version, location, dependencies
python -m pip uninstall pandas
deactivate # leave the environment
Path macOS / Linux Windows
interpreter .venv/bin/python .venv\Scripts\python.exe
installed packages .venv/lib/python3.13/site-packages/ .venv\Lib\site-packages\
tools installed in the venv .venv/bin/ruff, .venv/bin/pytest .venv\Scripts\ruff.exe
import sys
from importlib.metadata import entry_points, version
print(sys.prefix != sys.base_prefix) # True inside a virtual environment
print(version("pytest"), version("ruff")) # distribution names, not import names
(script,) = entry_points(group="console_scripts", name="pytest")
print(script.value) # the function the `pytest` command calls
Output
True
9.2.0 0.17.4
_pytest.config:_console_main
File Holds Written by Commit?
pyproject.toml direct dependencies as ranges, metadata, tool settings you, uv add yes
uv.lock every package, exact versions and hashes, all platforms uv lock yes
requirements.in direct dependencies (pip-tools style input) you yes
requirements.txt name==version pins (or a loose list) you, pip freeze, uv pip compile, uv export yes, for applications
pylock.toml a lock in the standard PEP 751 format uv export --format pylock.toml yes
.python-version the project’s Python version uv python pin yes
.venv/ installed packages uv, venv no: add it to .gitignore
Project kind dependencies in pyproject.toml Reproducible installs
library (others install it) ranges: pandas>=3.1,<4 a lock for your own CI only
application, service, analysis ranges commit uv.lock (or a fully pinned requirements.txt)
from packaging.specifiers import SpecifierSet
versions = ["3.0.2", "3.1.0", "3.1.1", "3.2.0", "4.0.0"]
for spec in [">=3.1,<4", "~=3.1", "~=3.1.0", "==3.1.*", "!=3.1.0,>=3.1"]:
print(f"{spec:<14}", [v for v in versions if v in SpecifierSet(spec)])
Output
>=3.1,<4 ['3.1.0', '3.1.1', '3.2.0']
~=3.1 ['3.1.0', '3.1.1', '3.2.0']
~=3.1.0 ['3.1.0', '3.1.1']
==3.1.* ['3.1.0', '3.1.1']
!=3.1.0,>=3.1 ['3.1.1', '3.2.0', '4.0.0']
Specifier Allows
==3.1.1 exactly 3.1.1 (a pin)
>=3.1,<4 3.1 up to, not including, 4.0
~=3.1 >=3.1, ==3.* (compatible release)
~=3.1.0 >=3.1.0, ==3.1.*
==3.1.* any 3.1.x
pkg[extra] the package plus an extra’s dependencies
; sys_platform == "win32" an environment marker: only on Windows
; python_version < "3.13" only on older Pythons
pyproject.toml
[project]
name = "shop" # the distribution name on PyPI
version = "0.3.0"
description = "Clean and summarize shop sales data."
readme = "README.md"
requires-python = ">=3.12"
license = "MIT" # an SPDX expression
authors = [{ name = "Ada Lovelace", email = "ada@example.com" }]
dependencies = [ # what users need, as ranges
"pandas>=3.1,<4",
"httpx>=0.28",
]
[project.optional-dependencies] # extras: pip install "shop[plots]"
plots = ["matplotlib>=3.11"]
[project.scripts] # console commands
shop = "shop.cli:main" # `shop` calls shop/cli.py: main()
[project.entry-points."shop.plugins"] # plugin hooks other packages can read
csv = "shop.readers:read_csv"
[project.urls]
Homepage = "https://example.com/shop"
[dependency-groups] # developer tools, never shipped (PEP 735)
dev = ["pytest>=9.2", "pytest-cov>=7.1", "ruff>=0.17", "mypy>=2.4"]
[build-system] # how to build the wheel
requires = ["hatchling>=1.27"]
build-backend = "hatchling.build"
[tool.ruff] # every tool reads its own [tool.NAME] table
line-length = 88
[tool.mypy]
strict = true
[tool.pytest]
testpaths = ["tests"]
Table Read by Holds
[project] installers, build tools, PyPI name, version, Python range, dependencies (PEP 621)
[project.optional-dependencies] installers extras
[project.scripts] installers commands created in .venv/bin
[project.entry-points.*] importlib.metadata.entry_points plugin registrations
[dependency-groups] uv, pip 25.1+ (--group dev) dev, test and docs tools
[build-system] uv build, pip the build backend: hatchling, setuptools, uv_build, flit
[tool.*] each tool settings for ruff, mypy, pytest, coverage, uv
import tomllib
text = """
[project]
name = "shop"
dependencies = ["pandas>=3.1,<4"]
[project.scripts]
shop = "shop.cli:main"
[tool.ruff]
line-length = 88
"""
config = tomllib.loads(text) # tomllib.load(f) needs a file opened with "rb"
module, func = config["project"]["scripts"]["shop"].split(":")
print(module, func, config["tool"]["ruff"]["line-length"])
Output
shop.cli main 88
Terminal
ruff check . # lint the project
ruff check --fix . # apply safe fixes
ruff check --fix --unsafe-fixes . # also unsafe fixes: review the diff
ruff check --diff app.py # show fixes, change nothing
ruff check --select I --fix . # sort imports only
ruff check --statistics . # findings per rule
ruff check --watch . # re-lint on every save
ruff check --add-noqa . # silence every current finding (adopting ruff)
ruff format . # format like Black
ruff format --check . # exit 1 if a file would change (CI)
ruff format --diff app.py # show formatting changes
ruff rule B006 # explain one rule
Prefix Family Catches
E, W pycodestyle E501 long line, E711 == None, E722 bare except, W291 trailing spaces
F Pyflakes F401 unused import, F821 undefined name, F841 unused variable
I isort I001 unsorted imports
B flake8-bugbear B006 mutable default, B008 call in a default, B023 loop variable in a closure, B905 zip without strict
UP pyupgrade UP006 List → list, UP045 Optional → X | None, UP032 f-strings
SIM flake8-simplify SIM115 open without with, SIM108 ternary
C4 flake8-comprehensions C416 needless comprehension
PTH flake8-use-pathlib PTH118 os.path.join, PTH123 open()
RUF ruff’s own RUF005 unpacking instead of +, RUF100 unused noqa
N pep8-naming N802 function name not snake_case
S flake8-bandit (security) S602 shell=True, S608 SQL built with strings
PD, NPY pandas-vet, NumPy NPY002 legacy np.random calls
pyproject.toml
[tool.ruff]
line-length = 88
target-version = "py312"
extend-exclude = ["notebooks/scratch"]
[tool.ruff.lint]
select = ["E", "W", "F", "I", "B", "UP", "SIM", "C4", "PTH", "RUF", "S"]
ignore = ["E501"] # let the formatter handle line length
[tool.ruff.lint.per-file-ignores]
"tests/**" = ["S101"] # S101 flags assert; fine in tests
[tool.ruff.lint.isort]
known-first-party = ["shop"]
[tool.ruff.format]
quote-style = "double"
docstring-code-format = true

Silence one finding with # noqa: B006 at the end of the line. ruff’s default rule set is only E4, E7, E9 and F: select more on purpose.

Command Does
mypy src/ check the package
mypy --strict src/ require hints everywhere, no implicit Any
mypy --check-untyped-defs legacy.py check bodies of functions without hints
uv run mypy with files = ["src", "tests"] in [tool.mypy]

The full syntax and configuration are on the type hints page.

pre-commit runs checks on the staged files before each git commit and blocks the commit when one fails.

.pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files # blocks big data files by accident
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.4 # match the ruff version in your lock
hooks:
- id: ruff-check
args: [--fix]
- id: ruff-format
- repo: local
hooks:
- id: mypy
name: mypy
entry: uv run mypy
language: system
types: [python]
pass_filenames: false
Terminal
uv tool install pre-commit # or: uv add --dev pre-commit
pre-commit install # adds the git hook to this repository
pre-commit run --all-files # run every hook on every file now
pre-commit autoupdate # bump the rev: of each repo
git commit --no-verify # skip the hooks once (avoid)

A minimal CI job runs the same checks: uv sync --locked, uv run ruff check ., uv run ruff format --check ., uv run mypy, uv run pytest.

src layout
shop/ # the repository
├── pyproject.toml
├── uv.lock
├── README.md
├── .python-version
├── src/
│ └── shop/ # the import package: `import shop`
│ ├── __init__.py # runs on import; __version__, public names
│ ├── __main__.py # `python -m shop`
│ ├── cli.py # argparse; main() for [project.scripts]
│ ├── cleaning.py
│ └── py.typed # empty marker: "this package ships type hints"
└── tests/
├── conftest.py
└── test_cleaning.py
Choice Why
code under src/ tests import the installed package, not files that happen to sit in the working folder
uv sync or pip install -e . an editable install: code changes apply without a reinstall
__init__.py marks a regular package; keep it light (imports run on every import shop)
__main__.py with raise SystemExit(main()) python -m shop works and returns an exit code
py.typed mypy and pyright then use your hints for users of the package
if __name__ == "__main__": in scripts importing the file does not run the program
Command Runs
python -m shop args shop/__main__.py
python -m shop.cli shop/cli.py as __main__
python -m venv .venv create an environment
python -m pip install x pip for exactly this interpreter
python -m pytest -q pytest; also puts the current folder on sys.path
python -m json.tool data/config.json pretty-print JSON
python -m http.server 8000 serve the current folder
python -m sqlite3 data/shop.db an SQLite shell (3.12+)
python -m timeit "sum(range(1000))" a micro-benchmark
python -m cProfile -s cumulative app.py a profile
python -m pdb app.py the debugger
python -m zipfile -l archive.zip list an archive
python -m uuid print a new UUID (3.12+)
Kind pyproject.toml Result
console command [project.scripts] shop = "shop.cli:main" a shop executable in .venv/bin
GUI command [project.gui-scripts] no console window on Windows
plugin [project.entry-points."shop.plugins"] csv = "shop.readers:read_csv" discoverable with entry_points(group="shop.plugins")
src/shop/cli.py
import argparse
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="shop")
parser.add_argument("path")
args = parser.parse_args(argv) # None: read sys.argv
print(f"reading {args.path}")
return 0 # the exit code
if __name__ == "__main__":
raise SystemExit(main())

After uv sync (or pip install -e .), shop data/sales.csv, uv run shop data/sales.csv and python -m shop.cli data/sales.csv all call the same main().

Trap Symptom Fix
bare pip install installs into another Python than the one you run python -m pip or uv pip / uv add
no environment active packages land in the system Python, or pip refuses (externally-managed-environment) a .venv, or uv run
ModuleNotFoundError after an install the editor or terminal uses another interpreter select .venv/bin/python; check sys.executable
a moved or renamed .venv broken paths, commands fail delete it and run uv sync
.venv committed to git a huge repository, machine-specific files add .venv/ to .gitignore
>= ranges without a lock a fresh install pulls new versions and breaks commit uv.lock
== pins in a library’s dependencies users get resolver conflicts ranges in libraries; pins in lock files
pyproject.toml edited by hand uv.lock is stale; uv sync --locked fails uv lock after manual edits
version("sklearn") PackageNotFoundError use the distribution name: version("scikit-learn")
flat layout imports tests pass locally against files, fail when installed the src layout and an editable install
python pkg/cli.py with relative imports ImportError: attempted relative import with no known parent package python -m pkg.cli
a file named like a package (pandas.py) the real package is shadowed rename the file
ruff format and ruff check disagree on line length endless churn one line-length in [tool.ruff]; ignore E501 when formatting
# noqa without a code hides every rule on that line # noqa: F401
pre-commit hooks not installed hooks never run pre-commit install once per clone
ruff version in pre-commit differs from the lock CI and local results differ keep rev: equal to the locked version

Pythonic code uses the language’s own tools: direct iteration, unpacking, comprehensions, context managers and the standard library. This page lists the idioms as “instead of… write…”, then shows each classic trap with a small demo, its symptom and its fix.

I want to… Use… Example
loop over items the items, not indexes for row in rows:
a counter in a loop enumerate(xs, start=1) for n, line in enumerate(f, start=1):
two lists in step zip(a, b, strict=True) for sid, t in zip(ids, temps, strict=True):
keys and values d.items() for k, v in d.items():
a default for a missing key d.get(k, default) cfg.get("timeout", 30)
build a list from a loop a comprehension [p.stem for p in paths if p.suffix == ".csv"]
sum or count without a list a generator expression sum(r["qty"] for r in rows)
“is there any…?” / “are all…?” any() / all() any(t > 30 for t in temps)
the first match or None next(gen, None) next((r for r in rows if r["id"] == k), None)
swap values tuple unpacking a, b = b, a
head and rest star unpacking first, *rest = items
join strings sep.join(parts) ", ".join(names)
format values f-strings f"{total:,.2f}"; f"{x=}" to debug
open a file with with open(p, encoding="utf-8") as f:
build paths pathlib.Path Path("data") / "sales.csv"
test a range a chained comparison if 0 <= pct <= 100:
test against several values in with a tuple or set if level in {"WARNING", "ERROR"}:
choose a value inline a conditional expression label = "high" if x > 10 else "low"
assign and test at once the walrus := while chunk := f.read(8192):
sort by a field key= sorted(rows, key=itemgetter("revenue"), reverse=True)
the largest by a field max(xs, key=...) max(stores, key=lambda s: s.size)
merge dicts a | b config = DEFAULTS | overrides
count / group Counter, defaultdict(list) Counter(levels).most_common(3)
ignore one expected error contextlib.suppress with suppress(FileNotFoundError): p.unlink()
keep the original cause raise ... from err raise ConfigError("bad file") from err
branch on the shape of data match case {"status": 200, "items": items}:
a record class @dataclass @dataclass(frozen=True)
an empty-container check truthiness if not rows:
a None check is None if value is None:
a float comparison math.isclose math.isclose(total, 0.3)
a fresh default list a None sentinel seen = [] if seen is None else seen
Instead of Write Why
for i in range(len(xs)): print(xs[i]) for x in xs: print(x) direct iteration
i = 0 … i += 1 for i, x in enumerate(xs): no manual counter
for i in range(len(a)): f(a[i], b[i]) for x, y in zip(a, b, strict=True): strict catches length bugs
for k in d: v = d[k] for k, v in d.items(): one lookup
if k in d: v = d[k] else: v = 0 v = d.get(k, 0) one call
d[k] = d[k] + 1 if k in d else 1 counts = Counter(xs) the standard tool
if k not in d: d[k] = [] then d[k].append(v) d.setdefault(k, []).append(v) or defaultdict(list)
out = [] + for + append out = [f(x) for x in xs if ok(x)] shorter, faster
sum([x * x for x in xs]) sum(x * x for x in xs) no temporary list
found = False + loop + break found = any(ok(x) for x in xs) intent is visible
s = "" + s += part s = "".join(parts) one copy
"Total: " + str(n) f"Total: {n}" readable
"%.2f" % x, "{:.2f}".format(x) f"{x:.2f}" modern formatting
f = open(p) … f.close() with open(p) as f: closes on errors too
os.path.join(a, b), os.path.exists(p) Path(a) / b, p.exists() objects, not strings
tmp = a; a = b; b = tmp a, b = b, a
x = xs[0]; rest = xs[1:] x, *rest = xs
if x > 0 and x < 10: if 0 < x < 10: chained comparison
if c == "a" or c == "b" or c == "c": if c in {"a", "b", "c"}:
if len(xs) == 0: if not xs: truthiness
if flag == True: if flag:
if x == None: if x is None: identity for singletons
type(x) == int isinstance(x, int) accepts subclasses
xs.sort(); top = xs[-1] top = max(xs) O(n)O(n), no mutation
sorted(xs, key=lambda r: r["k"]) sorted(xs, key=itemgetter("k")) faster, clearer
try: v = d[k] except KeyError: v = None v = d.get(k)
try: ... except: pass except SpecificError: or contextlib.suppress(...) does not hide bugs
raise NewError(str(e)) raise NewError("context") from e keeps the traceback chain
print("x =", x) while debugging print(f"{x=}") shows the expression
lambda assigned to a name def a real name in tracebacks
a = {**a, **b} a = a | b (a new dict) or a |= b |= mutates the dict: other names that refer to it see the change
if/elif on dict keys and types match with mapping and class patterns structure is visible
a class with only __init__ storing fields @dataclass free __repr__, __eq__
global counter in functions return values, or a class testable
from collections import Counter
from operator import itemgetter
rows = [
{"store": "S01", "region": "North", "revenue": 304.09},
{"store": "S07", "region": "East", "revenue": 2598.0},
{"store": "S10", "region": "West", "revenue": 66.49},
]
for n, row in enumerate(rows, start=1):
print(n, row["store"], f"{row['revenue']:>9,.2f}")
best = max(rows, key=itemgetter("revenue"))
print(best["store"], any(r["revenue"] > 1000 for r in rows))
print(sum(r["revenue"] for r in rows))
first, *others = sorted(r["store"] for r in rows)
print(first, others, Counter(r["region"] for r in rows).most_common(1))
print(next((r["store"] for r in rows if r["region"] == "South"), None))
config = {"timeout": 30, "retries": 3} | {"retries": 5}
print(config, f"{len(rows)=}")
Output
1 S01 304.09
2 S07 2,598.00
3 S10 66.49
S07 True
2968.58
S01 ['S07', 'S10'] [('North', 1)]
None
{'timeout': 30, 'retries': 5} len(rows)=3
def describe(response: dict) -> str:
match response: # structural pattern matching
case {"status": 200, "items": [first, *_]}:
return f"ok, first item {first}"
case {"status": 200, "items": []}:
return "ok, empty"
case {"status": 429 | 503 as code}:
return f"retry later ({code})"
case _:
return "unexpected"
print(describe({"status": 200, "items": ["P001", "P002"]}))
print(describe({"status": 429}), "|", describe({"status": 200, "items": []}))
Output
ok, first item P001
retry later (429) | ok, empty

EAFP means “easier to ask forgiveness than permission”: try the operation and handle the exception. LBYL means “look before you leap”: check first, then act.

LBYL EAFP
shape if path.exists(): read(path) try: read(path) except FileNotFoundError: ...
best when the check is cheap, exact and a business rule only the operation itself knows what is valid
risk the world changes between check and act (race) a broad except hides real bugs
typical uses blank lines, value ranges, permissions parsing numbers and dates, files, dict keys, network calls
import math
def parse_price(text: str) -> float | None:
try: # EAFP: float() knows every valid spelling
value = float(text.strip().removeprefix("$").replace(",", ""))
except ValueError:
return None
else: # runs only when no exception happened
return value if math.isfinite(value) and value >= 0 else None # LBYL rules
print([parse_price(t) for t in ["$79.99", "$1,299.00", "N/A", "nan", "-5"]])
Output
[79.99, 1299.0, None, None, None]

Keep the try block to the one line that can fail. Catch the narrowest exception. Put the follow-up code in else:.

Six classic traps have their full demo on the page where the concept is taught. This table gives the symptom, the fix and the link. The traps after it have their demo here; demos with deliberately bad code say so in a comment.

Trap Symptom Fix Demo
mutable default argument def f(x, out=[]) state leaks between calls default to None, create the list inside (ruff B006) defaults
late binding: [lambda: n for n in range(3)] every function sees the last loop value bind now: lambda n=n: n, partial or a factory (ruff B023) closures
total += x inside a function UnboundLocalError: cannot access local variable 'total' return the new value, or keep state in an object scope
b = a, [[0] * 3] * 3, copy.copy of nested data a change to the “copy” changes the original a comprehension per row; copy.deepcopy copying and aliasing
0.1 + 0.2 == 0.3, round(2.675, 2), round(2.5) False, 2.67, 2 math.isclose, Decimal("..."); halves round to even numbers, rounding
x == 1 or 2 always truthy x in (1, 2) syntax gotchas
a = "hello world"
b = " ".join(["hello", "world"]) # built at runtime: a different object
print(a == b, a is b) # equal values, different objects
x = [1, 2]
y = x # the same object, not a copy
z = [1, 2] # an equal, separate list
print(y is x, z is x, z == x)
Output
True False
True False True

Symptom: a comparison works in one place and fails in another. Fix: == compares values; is compares identity. Use is only for None, True, False and sentinels. x is "text" with a literal triggers a SyntaxWarning.

small_a, small_b = int("256"), int("256")
big_a, big_b = int("257"), int("257")
print(small_a is small_b, big_a is big_b, big_a == big_b)
Output
True False True

Symptom: is seems to work for small numbers and then fails. CPython keeps one shared object for each integer from -5 to 256, so is happens to be True there. Constants inside one script can also be shared. Fix: never compare numbers or strings with is.

Changing a collection while looping over it

Section titled “Changing a collection while looping over it”
codes = [-999, -999, 21, 22]
for c in codes: # bad: removing shifts the items under the loop
if c == -999:
codes.remove(c)
print(codes)
codes = [-999, -999, 21, 22]
codes = [c for c in codes if c != -999] # build a new list
print(codes)
Output
[-999, 21, 22]
[21, 22]
stock = {"P001": 0, "P002": 5, "P003": 0}
for product_id in stock: # bad: the dict changes size during iteration
if stock[product_id] == 0:
del stock[product_id]
Output
RuntimeError: dictionary changed size during iteration
stock = {"P001": 0, "P002": 5, "P003": 0}
for product_id in list(stock): # loop over a copy of the keys
if stock[product_id] == 0:
del stock[product_id]
print(stock, {k: v for k, v in {"a": 0, "b": 1}.items() if v})
Output
{'P002': 5} {'b': 1}

Symptom: a list loop silently skips items; a dict or set loop raises RuntimeError. Fix: build a new collection with a comprehension, or loop over a copy (list(d), xs[:]).

x = 5
print(1 < x < 10, (1 < x) < 10) # same result here, by luck
print(3 > 2 > 1, (3 > 2) > 1) # 3 > 2 and 2 > 1, versus True > 1
print(1 < 3 > 2) # legal: means 1 < 3 and 3 > 2
Output
True True
True False
True

Symptom: adding parentheses changes the answer; a < b > c reads strangely. a < b < c means a < b and b < c, while (a < b) < c compares a bool with c. Fix: use chains only for ranges (low <= x <= high); write other combinations with and.

import sys
def stop() -> None:
sys.exit(1) # raises SystemExit
try:
stop()
except: # bad: also catches SystemExit and KeyboardInterrupt (Ctrl+C)
print("bare except swallowed the exit")
try:
try:
stop()
except Exception: # better: SystemExit is not an Exception subclass
print("not printed")
except SystemExit as exit_request:
print("exit passed through with code", exit_request.code)
Output
bare except swallowed the exit
exit passed through with code 1

Symptom: Ctrl+C does not stop the program, sys.exit() is ignored, and typos such as NameError vanish. Fix: catch the specific exception (ValueError, KeyError, OSError); use except Exception as err: plus logging only at the top level of a program (ruff E722).

prices = [249.0, 14.99, 79.99]
result = prices.sort() # bad: sorts in place and returns None
print(result, prices, sorted([3, 1, 2]))
Output
None [14.99, 79.99, 249.0] [1, 2, 3]

Symptom: a variable is unexpectedly None. In-place methods (list.sort, list.append, dict.update, random.shuffle) return None. Fix: use the in-place call alone, or the copying form (sorted, a | b).

More number and truthiness traps (bool("False"), -7 // 2, money rounding) are on the syntax and types page.

Trap Symptom Fix
int("3.5") ValueError int(float("3.5")), or Decimal
["a" "b", "c"] a missing comma joins strings: ['ab', 'c'] one item per line, trailing commas
zip(a, b) with different lengths extra items vanish silently zip(a, b, strict=True)
a generator used twice the second pass is empty store a list, or call the function again
a class attribute items = [] all instances share one list create it in __init__ or with field(default_factory=list)
t = ([1],); t[0] += [2] TypeError, but the list changed anyway t[0].append(2)
except E as err: then err after the block NameError: err is deleted save it: error = err
__eq__ defined without __hash__ instances become unhashable @dataclass(frozen=True) or define __hash__
x == float("nan") always False math.isnan(x); pandas isna()
datetime.now() naive local time datetime.now(UTC)
open() without encoding works on one OS, fails on another encoding="utf-8"
a file named random.py or pandas.py AttributeError from the real module rename your file
from module import * names silently overwrite each other explicit imports
print instead of return the caller gets None return values; print at the edge
a huge try block the wrong line’s error is caught one risky line per try
recursion on deep data RecursionError at about 1,000 levels a loop with an explicit stack
sum() of floats in a loop by hand tiny drift versus sum sum (compensated since 3.12) or math.fsum

How to write a plain Python class for any job: a config object, an API client, a domain record or a model. Special methods are on the dunder methods page, and record classes on data containers.

I want to… Use… Example
define a class class Name: with a CapWords name class ApiClient:
set the starting state of each object def __init__(self, ...): self.base_url = base_url
create an instance call the class client = ApiClient("https://api.example.com")
see what an instance stores vars(obj) (same as obj.__dict__) {'base_url': '...', 'timeout': 5.0}
check the class of an object isinstance(obj, Cls); type(obj) for the exact class isinstance(u, User)
read an attribute by a string name getattr(obj, name, default) getattr(cfg, "debug", False)
share one constant across all instances a class attribute MAX_RETRIES = 3
give each instance its own list or dict create it in __init__ self.headers = {}
accept an optional mutable argument default None, then build it self.tags = list(tags) if tags else []
force arguments to be named * in the signature def __init__(self, url, *, timeout=5.0)
count or register all instances a class attribute changed through the class User.count += 1
build an object from a dict, a file or env vars @classmethod alternative constructor Config.from_env()
a helper that needs no instance or class @staticmethod, or a module function Slug.is_valid("a-b")
a computed attribute without () @property order.total
validate every assignment of an attribute @property plus @name.setter user.age = -1 raises ValueError
a read-only attribute @property with no setter AttributeError on assignment
compute an expensive value once per object @functools.cached_property report.summary
mark a name as internal one leading underscore self._session, _parse()
avoid a name clash in subclasses two leading underscores (name mangling) self.__cache → _Base__cache
avoid a keyword or built-in name one trailing underscore class_, type_, id_
hint “an instance of this class” typing.Self def from_env(cls) -> Self:
hint a class attribute typing.ClassVar count: ClassVar[int] = 0
hint a constant that must not change typing.Final MAX_RETRIES: Final = 3
name the class in its own body Self, or a quoted name "Node" children: list["Node"]
return the object for chaining return self query.where(...).limit(10)
show the object clearly in logs __repr__ User(name='ada', age=36)
a class mostly made of fields @dataclass see data containers
copy an object copy.copy(obj), copy.deepcopy(obj) deep copy for nested lists
list the public methods [n for n in dir(obj) if not n.startswith("_")]
from typing import ClassVar, Self
class User:
"""A user account.""" # docstring: help(User) shows it
MIN_AGE: ClassVar[int] = 13 # class attribute: one value for all users
count: ClassVar[int] = 0 # class-wide counter
def __init__(self, name: str, age: int, *, admin: bool = False) -> None:
self.name = name # instance attributes: one set per object
self.age = age
self.admin = admin
User.count += 1 # change a counter through the class
def greet(self) -> str: # instance method: works on self
return f"Hi, {self.name}"
@classmethod
def from_dict(cls, data: dict[str, object]) -> Self: # alternative constructor
return cls(str(data["name"]), int(str(data["age"]))) # cls: subclass-safe
@staticmethod
def is_valid_name(name: str) -> bool: # static method: no self, no cls
return name.isidentifier()
@property
def is_adult(self) -> bool: # computed on every read, no parentheses
return self.age >= 18
def __repr__(self) -> str: # developer view: print(), logs, the REPL
return f"{type(self).__name__}(name={self.name!r}, age={self.age!r})"
u = User.from_dict({"name": "ada", "age": "36"})
print(u, u.greet(), u.is_adult, User.is_valid_name("ada lovelace"), User.count)
Output
User(name='ada', age=36) Hi, ada True False 1
Piece Syntax Notes
class statement class Name: runs the body once and binds a class object to Name
initializer def __init__(self, ...) fills a new object; must return None
instance attribute self.x = value usually created in __init__
class attribute x = value in the body stored in vars(Cls); shared
instance method def m(self, ...) obj.m(a) is Cls.m(obj, a)
class method @classmethod def m(cls, ...) gets the class; works through subclasses
static method @staticmethod def m(...) gets nothing extra
property @property def x(self) read as obj.x
docstring first string in the body help(Cls), Cls.__doc__
class Reading:
unit = "°C"
def __init__(self, value: float) -> None:
self.value = value
r = Reading(21.5)
print(vars(r), "unit" in vars(r), "unit" in vars(Reading)) # instance vs class
r.unit = "K" # creates an instance attribute that shadows the class value
print(r.unit, Reading.unit, Reading(0.0).unit)
del r.unit # removes the instance value: the class value shows again
print(r.unit, type(r).__name__, getattr(r, "missing", "n/a"))
Output
{'value': 21.5} False True
K °C °C
°C Reading n/a

Reading obj.name searches, in order:

Step Where Found when
1 a data descriptor on the class (@property) the class defines a property with that name
2 the instance namespace, vars(obj) self.name = ... ran
3 the class, then each base in type(obj).__mro__ a method or a class attribute
4 __getattr__, if the class defines it fallback for missing names
5 nothing AttributeError: 'C' object has no attribute 'name'

obj.name = value writes to vars(obj), unless the class has a property (or another data descriptor) with that name; then its setter runs.

Built-in Does Example
vars(obj) the instance namespace (a dict) vars(cfg)
hasattr(obj, "x") True if lookup finds x hasattr(resp, "json")
getattr(obj, "x", default) lookup by a string name getattr(settings, key, None)
setattr(obj, "x", value) assignment by a string name for k, v in d.items(): setattr(cfg, k, v)
delattr(obj, "x") del obj.x by name
type(obj) the exact class type(u) is User
isinstance(obj, Cls) Cls or a subclass; a tuple means “any of” isinstance(x, (int, float))
dir(obj) all names lookup can find, sorted tab completion
obj.__class__, Cls.__name__, Cls.__module__ class, its name, its module type(self).__name__ in a repr
class Cart:
tax_rate = 0.2 # immutable shared default: safe
items_wrong: list[str] = [] # BUG: one list for every cart
created = 0
def __init__(self, owner: str) -> None:
self.owner = owner
self.items: list[str] = [] # right: one list per cart
Cart.created += 1 # right: changes the class counter
self.created += 1 # wrong: reads the class value, writes an instance attribute
a, b = Cart("ada"), Cart("bob")
b.tax_rate = 0.1 # b gets its own value; a still sees the class value
a.items_wrong.append("pen") # mutates the shared list
print(a.tax_rate, b.tax_rate, b.items_wrong, a.items is b.items)
print(Cart.created, b.created)
Output
0.2 0.1 ['pen'] False
2 3
Operation Effect
obj.x (read) the instance value if any, else the class value
obj.x = v creates or replaces an instance attribute; the class value is untouched
Cls.x = v changes the value for every instance without its own x
obj.x.append(v) mutates the object that lookup found; a class list is shared by all
self.n += 1 reads the class value, writes an instance attribute: the class counter does not move
Cls.n += 1 or type(self).n += 1 changes the class counter (type(self) gives each subclass its own counter)

Good class attributes: constants (MAX_RETRIES = 3), defaults that instances may shadow, registries and counters changed through the class, and type hints marked ClassVar.

Instance method Class method Static method
Decorator none @classmethod @staticmethod
First parameter self (the instance) cls (the class) none
Called as obj.m() Cls.m() or obj.m() Cls.m() or obj.m()
Reads instance state yes no no
Sees the subclass through type(self) yes: cls is the subclass no
Typical use behavior of one object alternative constructors, class-wide settings a helper of the class topic
Often better as — — a module-level function

Alternative constructors you already use:

Call Builds
dict.fromkeys(["a", "b"], 0) {'a': 0, 'b': 0}
datetime.fromisoformat("2024-05-01T13:30:00") a datetime
datetime.fromtimestamp(0, tz=UTC) a datetime from Unix time
date.today(), Path.cwd(), Path.home() from the environment
int.from_bytes(b"\x01\x00", "big") 256
bytes.fromhex("ff00"), float.fromhex(...) from text
Decimal.from_float(0.1), Fraction.from_float(0.5) exact numbers
pd.DataFrame.from_records(rows), pd.DataFrame.from_dict(d) a DataFrame
import os
from collections.abc import Iterable, Mapping
from typing import Self
class ApiClient:
def __init__(
self,
base_url: str, # required
*, # everything after * is keyword-only
timeout: float = 5.0, # optional, immutable default
headers: Mapping[str, str] | None = None, # optional mutable: default None
retries: int = 3,
) -> None:
if not base_url.startswith(("http://", "https://")):
raise ValueError(f"base_url must start with http(s)://, got {base_url!r}")
self.base_url = base_url.rstrip("/") # normalize once
self.timeout = timeout
self.headers = dict(headers or {}) # copy: the caller's dict stays separate
self.retries = retries
self._calls = 0 # internal state starts here too, never later
@classmethod
def from_env(cls, environ: Mapping[str, str] = os.environ) -> Self:
return cls(environ["API_URL"], timeout=float(environ.get("API_TIMEOUT", "5")))
@classmethod
def from_pairs(cls, base_url: str, pairs: Iterable[tuple[str, str]]) -> Self:
return cls(base_url, headers=dict(pairs))
def url(self, path: str) -> str:
return f"{self.base_url}/{path.lstrip('/')}"
env = {"API_URL": "https://api.example.com/", "API_TIMEOUT": "2.5"}
c = ApiClient.from_env(env) # inject the mapping: testable without real env vars
print(c.url("/users/7"), c.timeout, c.headers)
print(ApiClient.from_pairs("http://localhost:8000", [("Accept", "json")]).headers)
try:
ApiClient("api.example.com")
except ValueError as err:
print(err)
Output
https://api.example.com/users/7 2.5 {}
{'Accept': 'json'}
base_url must start with http(s)://, got 'api.example.com'
Pattern Code Why
required, then optional def __init__(self, url, timeout=5.0) defaults go last
keyword-only options def __init__(self, url, *, timeout=5.0) calls read clearly; you can reorder options later
mutable default tags=None → self.tags = list(tags or []) tags=[] is shared by every call
copy what you store self.headers = dict(headers) outside changes do not leak in
validate early raise ValueError(...) in __init__ or a setter a bad object never exists
set every attribute in __init__ self._cache = None hasattr checks and typos stay rare
keep __init__ cheap no network, no file reads build in from_file() / connect() instead
many ways to build @classmethod constructors that call cls(...) one __init__ stays the single source of truth
delegate to the parent super().__init__(...) see inheritance
mostly fields @dataclass writes __init__, __repr__ and __eq__ for you

__new__ creates the object and __init__ fills it. Override __new__ only to subclass an immutable type (int, str, tuple) or to control instance creation (caching).

from functools import cached_property
class Product:
def __init__(self, name: str, price: float) -> None:
self.name = name
self.price = price # runs the setter: new objects are validated too
@property
def price(self) -> float: # getter
return self._price # stored under another name
@price.setter
def price(self, value: float) -> None: # setter: the same name
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError(f"price must be a number, got {type(value).__name__}")
if value < 0:
raise ValueError(f"price must be >= 0, got {value}")
self._price = float(value)
@property
def slug(self) -> str: # read-only: no setter
return self.name.lower().replace(" ", "-")
class Report:
def __init__(self, values: list[float]) -> None:
self.values = values
@cached_property
def total(self) -> float: # runs once, then stored in vars(self)
print("computing...")
return round(sum(self.values), 2)
p = Product("USB Cable", 9.99)
for bad in (-1, "9.99"):
try:
p.price = bad
except (ValueError, TypeError) as err:
print(type(err).__name__, err)
print(p.price, p.slug)
try:
p.slug = "x"
except AttributeError as err:
print(err)
rep = Report([79.99, 249.0])
print(rep.total, rep.total, "total" in vars(rep))
Output
ValueError price must be >= 0, got -1
TypeError price must be a number, got str
9.99 usb-cable
property 'slug' of 'Product' object has no setter
computing...
328.99 328.99 True
Pattern Code Use
computed, read-only @property only full_name, total, is_expired
validated attribute @property + @x.setter storing self._x prices, ports, ages, ranges
validate in __init__ too self.x = x (not self._x = x) the setter checks new objects
normalize on write self._email = value.strip().lower() one canonical form
deleter @x.deleter rare: clean up on del obj.x
computed once per object @functools.cached_property parsed config, a summary; del obj.x resets it
the same check on many attributes a descriptor class see dunder methods
a plain stored value a plain attribute add a property later without changing callers

Do not write get_x() / set_x() methods. Start with a plain attribute. Turn it into a property when it needs a check; callers do not change.

Name Meaning Enforced?
name public interface —
_name internal: do not use from outside no, a convention; from m import * skips module-level _names
__name mangled to _ClassName__name inside the class body only the rename; not privacy
__name__ Python’s special names (__init__, __repr__) never mangled; do not invent new ones
name_ avoids a keyword or built-in (class_); a learned attribute in scikit-learn (coef_) no
CapWords class names: HttpClient, UserRepository PEP 8
UPPER_CASE constants: MAX_RETRIES PEP 8; Final makes type checkers enforce it
class Base:
def __init__(self) -> None:
self.__calls = 0 # stored as _Base__calls
def tick(self) -> int:
self.__calls += 1
return self.__calls
class Child(Base):
def __init__(self) -> None:
super().__init__()
self.__calls = "child data" # stored as _Child__calls: no clash
c = Child()
print(c.tick(), sorted(vars(c)), hasattr(c, "__calls"), c._Base__calls)
Output
1 ['_Base__calls', '_Child__calls'] False 1

Mangling rewrites identifiers in the class body (also other.__x), never strings: getattr(obj, "__x") is not rewritten. Use it only to protect internals of a class meant for subclassing. Use _x everywhere else.

Hint Meaning
def save(user: User) -> None a class is a type
-> Self (from typing) “an instance of the class this method runs on”; alternative constructors, chaining, __enter__
-> "Node" a quoted forward reference, before the class name exists
from __future__ import annotations annotations are stored as strings and not evaluated; no quotes needed (3.14 defers evaluation by default)
x: ClassVar[int] = 0 a class attribute, not a per-instance field (matters for dataclasses)
MAX: Final = 3 a constant; type checkers reject reassignment
self.items: list[str] = [] annotate an instance attribute where you create it
type[User] the class itself, not an instance: def make(cls: type[User]) -> User
@typing.override (3.12+) marks a method that must override a parent method
from typing import Self
class Query:
def __init__(self, table: str) -> None:
self.table = table
self.filters: list[str] = []
self.max_rows: int | None = None
def where(self, condition: str) -> Self: # Self: chaining keeps the subclass type
self.filters.append(condition)
return self
def limit(self, n: int) -> Self:
self.max_rows = n
return self
def sql(self) -> str:
where = f" WHERE {' AND '.join(self.filters)}" if self.filters else ""
limit = f" LIMIT {self.max_rows}" if self.max_rows is not None else ""
return f"SELECT * FROM {self.table}{where}{limit}"
print(Query("orders").where("amount > 100").where("region = 'EU'").limit(5).sql())
Output
SELECT * FROM orders WHERE amount > 100 AND region = 'EU' LIMIT 5
Error (last traceback line) Typical cause Fix
TypeError: C.m() takes 0 positional arguments but 1 was given self missing in def m(): def m(self):
NameError: name 'x' is not defined inside a method wrote x instead of self.x self.x
TypeError: C.__init__() missing 1 required positional argument: 'y' an argument missing in C(...) pass it or give a default
TypeError: C.__init__() takes 2 positional arguments but 3 were given an option is keyword-only C(a, timeout=3)
AttributeError: 'C' object has no attribute 'x' typo, never set, or a mangled __x read outside set it in __init__; check vars(obj)
AttributeError: property 'x' of 'C' object has no setter assigning a read-only property, or the setter has another name add @x.setter with the same name
RecursionError: maximum recursion depth exceeded the getter or setter of x uses self.x store the value in self._x
TypeError: __init__() should return None, not 'C' return self in __init__ no return in __init__
AttributeError: 'NoneType' object has no attribute 'limit' a chained method does not return self return self
NameError: name 'C' is not defined at the def line (3.12–3.13) -> C inside the body of class C -> Self or -> "C"
  • Missing self. Symptom: “takes 0 positional arguments but 1 was given”. Fix: the first parameter of an instance method is self.
  • Mutable class attribute. Symptom: one object’s list changes every object. Fix: create lists and dicts in __init__.
  • Mutable default argument. Symptom: def __init__(self, tags=[]) shares one list across calls. Fix: tags=None, then list(tags or []).
  • self.count += 1 on a class counter. Symptom: the class counter stays at 0. Fix: Cls.count += 1 or type(self).count += 1.
  • Hard-coded class name in a class method. Symptom: Sub.from_dict(...) returns a parent object. Fix: return cls(...).
  • Property that recurses. Symptom: RecursionError. Fix: the property x stores and reads self._x.
  • Setter skipped for new objects. Symptom: Product(price=-5) works. Fix: write self.price = price in __init__, not self._price.
  • bool passes a number check. Symptom: isinstance(True, int) is True, so retries=True is accepted. Fix: reject bool first.
  • cached_property goes stale. Symptom: the value does not follow changes in the data. Fix: use @property, or del obj.name after a change. It also does not work with __slots__.
  • __x is not private. Symptom: you expect protection and get a renamed attribute _C__x. Fix: use _x for internal names.
  • Memory address in output. Symptom: print(obj) shows <__main__.C object at 0x...>. Fix: add __repr__.
  • Heavy work in __init__. Symptom: you cannot create an object in a test without a network or a file. Fix: pass the data in, or build it in a @classmethod such as from_file().
  • A class of static methods only. Symptom: no state, every call is Utils.f(...). Fix: use a module of functions.
  • A class with __init__ and one method. Symptom: Thing(x).run() everywhere. Fix: write a function.

How classes reuse and specialize each other, and when not to inherit at all. Interfaces (ABCs and Protocols) are on ABC vs Protocol.

I want to… Use… Example
reuse a class and add to it a subclass class AdminUser(User): ...
replace a parent method define it again in the child def render(self): ...
extend a parent method super().method(...) return super().render() + footer
run the parent’s __init__ super().__init__(...) super().__init__(name, age)
pass unknown options up the chain **kwargs + super().__init__(**kwargs) cooperative __init__
see the lookup order Cls.__mro__ or Cls.mro() [c.__name__ for c in Cls.__mro__]
find which class defines a method walk the MRO next(c for c in Cls.__mro__ if "save" in vars(c))
list the direct parents Cls.__bases__ (User,)
list the direct children Cls.__subclasses__() plugin discovery
test “is some kind of” isinstance(obj, Base) isinstance(err, OSError)
test a class relation issubclass(Child, Base) issubclass(bool, int) → True
add one capability to many classes a mixin, listed first class Order(JsonMixin, Model)
reuse behavior without is-a composition: hold the part self.storage = storage
forward many calls to a held object __getattr__ delegation see dunder methods
make a custom dict or list collections.UserDict / UserList, or collections.abc class CaseInsensitiveDict(UserDict)
accept any object with the right methods duck typing def save(fp): fp.write(...)
choose behavior by the argument’s type functools.singledispatch @to_json.register
choose behavior by the object’s class a method override (polymorphism) shape.area()
force subclasses to write a method abc.ABC + @abstractmethod ABC vs Protocol
register every subclass on creation __init_subclass__ class CsvExporter(Exporter, fmt="csv")
mark an override for type checkers @typing.override (3.12+) mypy flags a typo in the name
stop further subclassing (type checkers) @typing.final @final class Token:
build an error family a base exception + subclasses class AppError(Exception)
class Notifier:
def __init__(self, sender: str) -> None:
self.sender = sender
def format(self, text: str) -> str:
return f"[{self.sender}] {text}"
def send(self, text: str) -> str: # a template: calls methods a child may override
return f"{self.channel()}: {self.format(text)}"
def channel(self) -> str: # a hook
return "log"
class EmailNotifier(Notifier):
def __init__(self, sender: str, to: str) -> None:
super().__init__(sender) # the parent sets its part
self.to = to # the child adds its own
def channel(self) -> str: # replace
return f"email to {self.to}"
def format(self, text: str) -> str: # extend
return super().format(text).upper()
n = EmailNotifier("billing", "ada@example.com")
print(n.send("invoice ready"))
print(vars(n), [c.__name__ for c in EmailNotifier.__mro__])
Output
email to ada@example.com: [BILLING] INVOICE READY
{'sender': 'billing', 'to': 'ada@example.com'} ['EmailNotifier', 'Notifier', 'object']
Child choice Code When
inherit write nothing the parent’s behavior fits
replace def m(self): ... without super() the behavior must differ
extend def m(self): r = super().m(); ... add a step before or after
hook the parent calls self._step(); the child overrides _step vary one step of a fixed algorithm
new method a name the parent lacks extra behavior only the child has

self is always the real object. A parent method that calls self.channel() runs the child’s version: this is how overrides plug into parent code.

Fact Detail
meaning “the next class after this one in type(self).__mro__”, not “my parent”
super().__init__(...) Python never calls the parent’s __init__ for you
works in instance methods, class methods, __init_subclass__, properties
zero-argument form only inside a method defined in a class body
super(Cls, self) the old explicit form; same meaning, rarely needed
Parent.method(self) a direct call: skips the MRO; breaks multiple inheritance
from typing import Self
class Child(Parent):
def __init__(self, *, extra: int = 0, **kwargs) -> None:
super().__init__(**kwargs) # the parent takes its options
self.extra = extra # then the child's part
@classmethod
def from_config(cls, config: dict) -> Self:
return super().from_config(config) # cls stays the subclass
@property
def label(self) -> str:
return super().label + "!" # extend a parent property

The MRO is the list of classes Python searches for an attribute, left to right. Python computes it with the C3 linearization when it creates the class.

class Base:
def save(self) -> str:
return "Base"
class Timestamped(Base):
def save(self) -> str:
return "Timestamped>" + super().save()
class Validated(Base):
def save(self) -> str:
return "Validated>" + super().save()
class Order(Timestamped, Validated): # a diamond: both parents share Base
pass
print([c.__name__ for c in Order.__mro__])
print(Order().save()) # super() in Timestamped reaches its sibling, Validated
print(next(c.__name__ for c in Order.__mro__ if "save" in vars(c))) # first match
print([c.__name__ for c in bool.__mro__], [c.__name__ for c in KeyError.__mro__])
Output
['Order', 'Timestamped', 'Validated', 'Base', 'object']
Timestamped>Validated>Base
Timestamped
['bool', 'int', 'object'] ['KeyError', 'LookupError', 'Exception', 'BaseException', 'object']
C3 rule Effect
a class comes before its parents Order before Timestamped
parents keep the order you list class C(A, B): A before B
each class appears once; a shared parent comes after all its children Base runs last, once
no order satisfies all rules TypeError when the class is created
class A:
pass
class B(A):
pass
class C(A, B): # A must come before B (listed order) and after B (B is a child of A)
pass
Output
TypeError: Cannot create a consistent method resolution order (MRO) for bases A, B

Every class in the chain takes its own keyword arguments and passes the rest on with super(). A root class ends the chain.

class Component: # the root: ends the chain
def __init__(self, **kwargs: object) -> None:
super().__init__(**kwargs) # object.__init__() rejects leftovers: a typo fails
def describe(self) -> list[str]:
return [] # no super(): object has no describe()
class Named(Component):
def __init__(self, *, name: str, **kwargs: object) -> None:
super().__init__(**kwargs)
self.name = name
def describe(self) -> list[str]:
return [f"name={self.name}", *super().describe()]
class Cached(Component):
def __init__(self, *, ttl: int = 60, **kwargs: object) -> None:
super().__init__(**kwargs)
self.ttl = ttl
def describe(self) -> list[str]:
return [f"ttl={self.ttl}", *super().describe()]
class Service(Named, Cached):
pass
s = Service(name="users", ttl=30)
print(s.describe(), [c.__name__ for c in Service.__mro__][:4])
try:
Service(name="users", tll=30) # typo in an option
except TypeError as err:
print(err)
Output
['name=users', 'ttl=30'] ['Service', 'Named', 'Cached', 'Component']
object.__init__() takes exactly one argument (the instance to initialize)
Why does the error name object?

No class in the chain takes tll, so it reaches object.__init__(), which accepts no arguments besides the instance. The message does not name the bad keyword, but a misspelled option fails loudly instead of being ignored.

Rule Why
every method in the chain calls super() once each class runs exactly once
a root class ends the chain without super().method() object has no such method
the same signature in every class of the chain any class can be next
__init__(self, *, own=..., **kwargs) + super().__init__(**kwargs) each class takes its keywords
keyword arguments only positional order changes with the MRO
never Parent.method(self) in the chain skips classes or runs one twice

A mixin is a small class that adds one capability. It is never used alone and relies on methods or attributes of its host class.

import json
class ReprMixin:
def __repr__(self) -> str: # works for any class with simple vars()
fields = ", ".join(f"{k}={v!r}" for k, v in vars(self).items())
return f"{type(self).__name__}({fields})"
class JsonMixin:
def to_json(self) -> str: # relies on the host storing JSON-friendly values
return json.dumps(vars(self), sort_keys=True)
class Customer(ReprMixin, JsonMixin): # mixins first, the main base last
def __init__(self, customer_id: str, plan: str) -> None:
self.customer_id = customer_id
self.plan = plan
c = Customer("C00001", "basic")
print(c, c.to_json())
Output
Customer(customer_id='C00001', plan='basic') {"customer_id": "C00001", "plan": "basic"}
Rule Example
one capability per mixin JsonMixin adds only to_json()
no __init__ and no own state (or a cooperative __init__) the host owns the data
name ends in Mixin LoginRequiredMixin, TransformerMixin
list it left of the main base class class View(LoginRequiredMixin, TemplateView)
document what it needs from the host “needs fit() and transform()”
Mixins in the wild Adds
socketserver.ThreadingMixIn one thread per request
collections.abc.Sequence, Mapping (as bases) index, count, get, items and more from a few methods
Django LoginRequiredMixin, PermissionRequiredMixin access checks on class-based views
scikit-learn TransformerMixin, ClassifierMixin fit_transform(), score()
from collections import UserDict
class LowerDict(dict): # dict's C code skips your __setitem__ in some paths
def __setitem__(self, key: str, value: object) -> None:
super().__setitem__(key.lower(), value)
class LowerUserDict(UserDict): # UserDict routes every write through __setitem__
def __setitem__(self, key: str, value: object) -> None:
super().__setitem__(key.lower(), value)
d, u = LowerDict(A=1), LowerUserDict(A=1)
d.update(B=2)
u.update(B=2)
d["C"] = 3
u["C"] = 3
print(sorted(d), sorted(u))
Output
['A', 'B', 'c'] ['a', 'b', 'c']
Want Base class
a dict with custom writes or reads collections.UserDict or collections.abc.MutableMapping
a list with custom writes collections.UserList or collections.abc.MutableSequence
a dict with a default for missing keys dict + __missing__, or collections.defaultdict
a str with extra methods only str (methods that return str return a plain str)
a value type such as Money composition: hold an int or a Decimal

Rule of thumb: inherit for is-a, when the child can replace the parent everywhere (Liskov substitution). Compose for has-a, for swappable parts and to reuse a few methods. When in doubt, compose.

class MemoryStorage:
def __init__(self) -> None:
self._data: dict[str, str] = {}
def get(self, key: str) -> str | None:
return self._data.get(key)
def set(self, key: str, value: str) -> None:
self._data[key] = value
class Cache: # has a storage; does not inherit one
def __init__(self, storage: MemoryStorage, prefix: str = "cache:") -> None:
self.storage = storage # swap in a Redis or file storage with the same methods
self.prefix = prefix
self.hits = 0
def get(self, key: str) -> str | None:
value = self.storage.get(self.prefix + key)
self.hits += value is not None
return value
def set(self, key: str, value: str) -> None:
self.storage.set(self.prefix + key, value)
cache = Cache(MemoryStorage())
cache.set("user:7", "ada")
print(cache.get("user:7"), cache.get("user:8"), cache.hits)
Output
ada None 1
Situation Choose Why
AdminUser and User inheritance an admin is a user everywhere
an exception family (NotFoundError(AppError)) inheritance except AppError catches all
a framework base class (TestCase, nn.Module, Django View) inheritance the framework calls your overrides
a service that uses a database, a cache or an HTTP client composition swap the part in tests and in production
a stack, a queue or a history that “is a list” composition inheriting list exposes sort(), insert(), clear()
one class per option (JsonCsvUploader, XmlS3Uploader) composition combinations multiply classes
a behavior chosen at run time composition (strategy) assign another object or function
one small method shared by many classes a mixin, or a function no state, no is-a
Sign of misused inheritance Symptom
the child turns off a parent method def append(self, x): raise NotImplementedError
two parents define the core method only one save() runs
the class name contains “And” ParserAndUploader
deep trees (four or more levels) the fragile base class problem: a parent change breaks distant children

Polymorphism means one call works on many types: each type gives its own behavior. Python finds the method at run time on the object’s class, so the types need no common base. This is duck typing: “if it has area(), it is a shape”.

import io
import math
class Circle:
def __init__(self, r: float) -> None:
self.r = r
def area(self) -> float:
return math.pi * self.r**2
class Square: # no common base class with Circle
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side**2
def total_area(shapes: list) -> float:
return round(sum(s.area() for s in shapes), 2) # any object with area()
def write_report(fp, lines: list[str]) -> None: # any object with write()
for line in lines:
fp.write(line + "\n")
buf = io.StringIO() # a file-like object in memory: a test double for a real file
write_report(buf, ["a", "b"])
print(total_area([Circle(1), Square(2)]), repr(buf.getvalue()))
print(len("abc"), len([1, 2]), len({"k": 1})) # len() is polymorphic: __len__
Output
7.14 'a\nb\n'
3 2 1
Style Code Note
just call it obj.area() AttributeError at the call if it is missing
LBYL (“look before you leap”) if callable(getattr(obj, "area", None)): check before long work
EAFP (“easier to ask forgiveness”) try: f = obj.area / except AttributeError: / else: f() guard only the lookup
EAFP, too wide try: obj.area() / except AttributeError: hides bugs inside area()
isinstance() on a concrete class if isinstance(obj, Circle): breaks duck typing; use a method or an ABC
type hint def total_area(shapes: list[HasArea]) a Protocol: see ABC vs Protocol

Duck typing in the standard library: json.dump() takes any object with write(); csv.reader() takes any iterable of strings; sum() takes any iterable; with takes any object with __enter__ and __exit__.

When behavior depends on the type of an argument you do not own, use functools.singledispatch instead of an isinstance() chain:

from datetime import date
from decimal import Decimal
from functools import singledispatch
@singledispatch
def to_json(value: object) -> object:
raise TypeError(f"cannot serialize {type(value).__name__}")
@to_json.register
def _(value: date) -> str: # dispatch on the first argument's type
return value.isoformat()
@to_json.register
def _(value: Decimal) -> str:
return str(value)
print(to_json(date(2024, 5, 1)), to_json(Decimal("9.99")))
Output
2024-05-01 9.99
class AppError(Exception):
"""Base of every error of this app: catch them all with one except."""
class NotFoundError(AppError, LookupError): # also a LookupError for old callers
def __init__(self, kind: str, key: object) -> None:
super().__init__(f"{kind} {key!r} not found")
self.kind, self.key = kind, key
try:
raise NotFoundError("user", 7)
except AppError as err:
print(err, "|", err.kind, isinstance(err, LookupError))
Output
user 7 not found | user True
  • Child __init__ replaces the parent’s. Symptom: AttributeError for an attribute the parent sets. Fix: call super().__init__(...).
  • super() is not “my parent”. Symptom: in a diamond, super() reaches a sibling class. Fix: read Cls.__mro__; design every class of the chain to cooperate.
  • Parent.method(self) in a chain. Symptom: a class runs twice or never. Fix: use super() in every class.
  • Root calls super().method(). Symptom: AttributeError: 'super' object has no attribute 'method'. Fix: the root class ends the chain.
  • Positional arguments in cooperative __init__. Symptom: values land in the wrong class when the MRO changes. Fix: keyword-only arguments and **kwargs.
  • Mixin on the right. Symptom: when the base class also defines the method (for example __repr__), the base’s version wins. Fix: list mixins before the main base class.
  • Impossible MRO. Symptom: TypeError: Cannot create a consistent method resolution order. Fix: list a child before its parent, or drop the redundant base.
  • Subclassing dict or list. Symptom: update(), __init__() or extend() skip your override. Fix: subclass UserDict / UserList or a collections.abc class.
  • Subclass breaks the contract. Symptom: code that works with the parent fails or gives wrong results with the child. Fix: keep the parent’s arguments, return types and errors; otherwise compose.
  • type(obj) is Base. Symptom: False for every subclass. Fix: isinstance(obj, Base).
  • isinstance() chains. Symptom: each new type means editing the chain. Fix: a method on each class, or singledispatch.
  • except AttributeError around a whole call. Symptom: real bugs inside the method are hidden. Fix: guard only the attribute lookup.
  • Deep hierarchies. Symptom: a small parent change breaks distant children. Fix: keep trees shallow; prefer composition.

Two ways to describe an interface. An ABC (abstract base class) is nominal: a class must inherit from it, and Python checks at run time that the required methods exist. A Protocol is structural: any class with matching methods fits, and a type checker (mypy, pyright) checks it before the code runs.

I want to… Use… Example
force subclasses to implement a method abc.ABC + @abstractmethod class Storage(ABC): ...
get an error before an incomplete object exists an ABC TypeError at Half()
share code between implementations concrete methods on the ABC def save_all(self, items): ...
an abstract property @property above @abstractmethod def extension(self) -> str: ...
an abstract class method @classmethod above @abstractmethod def from_url(cls, url): ...
list the methods still missing Cls.__abstractmethods__ frozenset({'get'})
count a class as a subclass without inheriting Base.register(Other) virtual subclass
accept any object with certain methods typing.Protocol class SupportsRead(Protocol): ...
type third-party objects you cannot edit a Protocol def load(fp: SupportsRead)
require an attribute, not a method a protocol with an annotation name: str
type a callback with keyword arguments a protocol with __call__ class OnEvent(Protocol): def __call__(...)
a generic protocol class Repo[T](Protocol): (3.12+) Repo[User]
use a protocol with isinstance() @runtime_checkable names only, not signatures
check “can I iterate / index / call it” collections.abc isinstance(x, Iterable)
type a parameter “any read-only mapping” collections.abc.Mapping def f(cfg: Mapping[str, str])
type “any iterable” collections.abc.Iterable def total(xs: Iterable[float])
get many methods from a few subclass a collections.abc class Sequence gives index, count, __iter__
check “is it a path” os.PathLike isinstance(p, os.PathLike)
check “is it hashable” collections.abc.Hashable isinstance([], Hashable) → False
a quick script plain duck typing just call the method
fail loudly when a protocol is not met run mypy or pyright mypy src/
from abc import ABC, abstractmethod
class Storage(ABC):
@property
@abstractmethod # innermost decorator
def scheme(self) -> str: ...
@abstractmethod
def get(self, key: str) -> bytes | None: ...
@abstractmethod
def put(self, key: str, data: bytes) -> None: ...
def url(self, key: str) -> str: # concrete method built on abstract parts
return f"{self.scheme}://{key}"
def copy(self, src: str, dst: str) -> None: # a template that every subclass gets
data = self.get(src)
if data is None:
raise KeyError(src)
self.put(dst, data)
class MemoryStorage(Storage):
scheme = "mem" # a class attribute satisfies the abstract property
def __init__(self) -> None:
self._data: dict[str, bytes] = {}
def get(self, key: str) -> bytes | None:
return self._data.get(key)
def put(self, key: str, data: bytes) -> None:
self._data[key] = data
s = MemoryStorage()
s.put("a.txt", b"hi")
s.copy("a.txt", "b.txt")
print(s.url("b.txt"), s.get("b.txt"), sorted(Storage.__abstractmethods__))
print(isinstance(s, Storage), MemoryStorage.__abstractmethods__ == frozenset())
Output
mem://b.txt b'hi' ['get', 'put', 'scheme']
True True

An incomplete subclass fails when you create an instance, not when you define the class:

class HalfStorage(Storage):
scheme = "half"
def get(self, key: str) -> bytes | None:
return None
print(sorted(HalfStorage.__abstractmethods__))
HalfStorage() # put() is missing
Output
['put']
TypeError: Can't instantiate abstract class HalfStorage without an implementation for abstract method 'put'
Fact Detail
needs ABC (or metaclass=ABCMeta) in the tree @abstractmethod alone does nothing
checked when at Cls(), not at class definition
what is checked that the names are overridden, not signatures or return types
abstract method with a body allowed; subclasses call it with super().method()
decorator order @property, @classmethod or @staticmethod above @abstractmethod
Cls.__abstractmethods__ a frozenset of names still missing
Base.register(Other) isinstance() says True; nothing is inherited or checked
__subclasshook__ lets an ABC accept classes by structure (how Sized and Iterable work)
an ABC with no abstract methods can be instantiated; use it only as a marker base
import io
from typing import Protocol
class SupportsRead(Protocol):
def read(self, size: int = -1, /) -> str: ...
class Named(Protocol):
name: str # an attribute member
def first_line(fp: SupportsRead) -> str: # no base class needed
return fp.read().splitlines()[0]
class FakeFile: # a test double: matches by structure
def read(self, size: int = -1, /) -> str:
return "header\nrow"
class Job:
def __init__(self, name: str) -> None:
self.name = name
def label(obj: Named) -> str:
return obj.name.upper()
print(first_line(io.StringIO("id,amount\n1,9.99")), first_line(FakeFile()))
print(label(Job("nightly-export")))
Output
id,amount header
NIGHTLY-EXPORT
Protocol form Code Use
methods def read(self) -> str: ... file-like, client-like objects
attributes name: str any object with that attribute
read-only attribute @property def name(self) -> str: ... accepts a property or a plain attribute
callable def __call__(self, event: str, *, retry: bool) -> None: ... callbacks with keyword arguments; Callable[...] cannot name them
generic class Repo[T](Protocol): def get(self, id: int) -> T: ... Repo[User], Repo[Order]
combined class ReadWrite(SupportsRead, SupportsWrite, Protocol): ... list Protocol again
explicit class FakeFile(SupportsRead): optional; mypy then checks the class body
from collections.abc import Callable
from typing import Protocol
class OnEvent(Protocol):
def __call__(self, name: str, *, retry: bool = False) -> None: ...
def subscribe(handler: OnEvent) -> None: ...
def log_event(name: str, *, retry: bool = False) -> None: ...
subscribe(log_event) # OK: same signature
subscribe(print) # mypy error: print has no retry parameter
Handler = Callable[[str], None] # Callable cannot express keyword-only parameters
from typing import Protocol, runtime_checkable
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
class Conn:
def close(self) -> None:
pass
class Liar:
close = 0 # not callable
class WrongSignature:
def close(self, force: bool) -> str: # needs an argument, returns str
return "closed"
print(isinstance(Conn(), Closeable), isinstance(Liar(), Closeable))
print(isinstance(WrongSignature(), Closeable), isinstance(open, Closeable))
Output
True True
True False
Caveat Detail
without the decorator isinstance() raises TypeError: Instance and class checks can only be used with @runtime_checkable protocols
checks only that each member name exists on the object
does not check signatures, return types, attribute types, even callable()
protocols with data members issubclass() raises TypeError: Protocols with non-method members don't support issubclass(). Non-method members: 'name'.
speed slower than a normal isinstance(): it inspects every member
a protocol itself Closeable() raises TypeError: Protocols cannot be instantiated
the safer run-time check callable(getattr(obj, "close", None))
ABC Abstract methods you write Mixin methods you get isinstance() is True for
Iterable __iter__ — list, tuple, str, dict, set, range, files, generators
Iterator __next__ __iter__ generators, iter(x), files, map(), zip()
Generator send, throw close, __iter__, __next__ generator objects
Sized __len__ — anything with __len__
Container __contains__ — anything with __contains__
Hashable __hash__ — int, str, tuple, frozen dataclasses; not list, dict, set
Callable __call__ — functions, methods, classes, objects with __call__
Collection __len__, __iter__, __contains__ — list, tuple, str, dict, set
Sequence __getitem__, __len__ __contains__, __iter__, __reversed__, index, count list, tuple, str, range, bytes
MutableSequence the above + __setitem__, __delitem__, insert append, extend, pop, remove, reverse, += list, deque, bytearray
Set __contains__, __iter__, __len__ <=, &, |, -, ^, isdisjoint set, frozenset, dict.keys()
MutableSet the above + add, discard remove, pop, clear, |=, &= set
Mapping __getitem__, __len__, __iter__ __contains__, keys, items, values, get, __eq__ dict, MappingProxyType, ChainMap
MutableMapping the above + __setitem__, __delitem__ pop, popitem, setdefault, update, clear dict, defaultdict, OrderedDict, Counter
Awaitable, AsyncIterable, AsyncIterator __await__, __aiter__, __anext__ — coroutines, async generators

The one-trick ABCs (Iterable, Iterator, Reversible, Sized, Container, Collection, Hashable, Callable, Generator, the async ones and Buffer) check by structure: a class with __len__ is Sized without inheriting. Sequence and Mapping need inheritance or register().

from collections.abc import Hashable, Iterable, Iterator, Mapping, Sequence, Sized
class Bag:
def __len__(self) -> int:
return 3
checks = {
"list is Sequence": isinstance([], Sequence),
"dict is Sequence": isinstance({}, Sequence),
"dict is Mapping": isinstance({}, Mapping),
"str is Iterable": isinstance("ab", Iterable),
"list is Iterator": isinstance([], Iterator),
"Bag is Sized": isinstance(Bag(), Sized),
"list is Hashable": isinstance([], Hashable),
}
for name, ok in checks.items():
print(f"{name:<18}{ok}")
Output
list is Sequence True
dict is Sequence False
dict is Mapping True
str is Iterable True
list is Iterator False
Bag is Sized True
list is Hashable False

Other ready-made interfaces:

Interface Module Means
os.PathLike os has __fspath__; pathlib.Path is one
contextlib.AbstractContextManager contextlib has __enter__ and __exit__
numbers.Number, Real, Integral numbers the numeric tower: isinstance(3, numbers.Real) is True
SupportsInt, SupportsFloat, SupportsIndex, SupportsAbs typing runtime-checkable protocols for conversions
io.IOBase, io.TextIOBase io real file objects
Buffer collections.abc (3.12+) supports the buffer protocol: bytes, bytearray, memoryview
ABC Protocol Duck typing
Relation nominal: must inherit (or register) structural: matching methods none
Checked by Python, at Cls() mypy or pyright, before running the call itself
Error for a missing method TypeError when you create the object a type-checker error AttributeError at the call
Shares code yes, concrete methods no (methods with bodies are only defaults for explicit subclasses) no
Works with third-party classes only with register() yes yes
isinstance() yes, real only with @runtime_checkable, names only hasattr() / callable(getattr(...))
Signatures checked no yes (by the type checker) no
Need Choose
a quick script, standard library style duck typing
your own family of classes that share code ABC with concrete methods
plugins that must implement a method, with an early clear error ABC
a function parameter that accepts objects you do not own Protocol
a test double without inheriting from the real class Protocol
a small interface per caller (interface segregation) several small Protocols
a run-time branch on capability collections.abc or callable(getattr(...))
both: shared code and structural typing an ABC for implementers, a Protocol for callers
  • @abstractmethod without ABC. Symptom: an incomplete subclass is created without error. Fix: inherit from ABC or use metaclass=ABCMeta.
  • Wrong decorator order. Symptom: an abstract property or class method is not enforced, or AttributeError at class creation. Fix: put @abstractmethod innermost, directly above def.
  • ABCs check names only. Symptom: def get(self) with the wrong parameters counts as an implementation. Fix: run mypy; write tests for each implementation.
  • Late error. Symptom: an incomplete subclass imports fine and fails only at Cls(). Fix: create one instance of each implementation in a test.
  • register() trusts you. Symptom: isinstance() is True, then AttributeError. Fix: use register() only for classes that really implement the interface.
  • Runtime protocol checks are shallow. Symptom: isinstance(obj, Closeable) is True for close = 0 or the wrong signature. Fix: rely on mypy; at run time also check callable().
  • isinstance() with a plain Protocol. Symptom: TypeError: Instance and class checks can only be used with @runtime_checkable protocols. Fix: add @runtime_checkable, or do not check at run time.
  • Protocol with data members and issubclass(). Symptom: TypeError: Protocols with non-method members don't support issubclass(). Non-method members: …. Fix: use isinstance() on an instance.
  • Positional-only mismatch. Symptom: mypy rejects io.StringIO for your read(self, size) protocol. Fix: mark parameters positional-only with / when callers pass them positionally.
  • isinstance(x, Iterable) misses old-style iterables. Symptom: a class with only __getitem__ is iterable but not Iterable. Fix: try iter(x) and catch TypeError.
  • str is a Sequence of str. Symptom: a function for “a list of names” accepts "ada" and loops over letters. Fix: check isinstance(x, str) first.
  • A fat interface. Symptom: implementations raise NotImplementedError for half the methods. Fix: split into small protocols.

Special methods (“dunder” methods, for double underscore) let your objects work with Python syntax and built-ins: len(x), x[i], a + b, with x:, for item in x. Python calls them for you; you rarely call them yourself.

I want to… Use… Example
show an object clearly in logs and the REPL __repr__ Money(1349, 'USD')
show friendly text to users __str__ 13.49 USD
support format specs in f-strings __format__(self, spec) f"{price:,.2f}"
compare by value __eq__; return NotImplemented for other types Money(5) == Money(5)
use objects as dict keys or in sets __hash__ from the same fields as __eq__ hash((self.cents, self.currency))
sort, min(), max() __lt__ + __eq__ + @functools.total_ordering sorted(versions)
len(x) __len__ len(playlist)
x[i], x[a:b], x["key"] __getitem__; test isinstance(key, slice) playlist[1:3]
x[k] = v, del x[k] __setitem__, __delitem__ a mutable store
for item in x __iter__ written as a generator yield from self._items
item in x __contains__ "ada" in team
control if x: __bool__, or only __len__ empty is falsy
call an object like a function __call__ retry(fetch)
set up and always clean up __enter__ / __exit__ with Transaction(db):
async with x: __aenter__ / __aexit__ an async DB session
a + b, a * k, a @ b __add__, __mul__, __matmul__ v1 + v2
2 * v, sum(xs) reflected __rmul__, __radd__ __rmul__ = __mul__
a += b in place __iadd__, return self a mutable accumulator
-v, abs(v) __neg__, __abs__ abs(v1 - v2)
decline an operand type return NotImplemented Python tries the other side
a fallback for missing attributes __getattr__ delegate to a wrapped object
block or check every assignment __setattr__ a read-only object
reuse a validated attribute on many classes a descriptor: __get__, __set__, __set_name__ price = Positive()
run code when a subclass is created __init_subclass__ a plugin registry
Cls[int] in type hints __class_getitem__ (or Generic / class C[T]:) Box[int]
a dict with defaults for missing keys subclass dict + __missing__ defaultdict, Counter
open(x), Path(x) on your object __fspath__ a class that names a file
control copy / pickle __copy__, __deepcopy__, __getstate__, __setstate__ drop an open socket before pickling
positional patterns in match __match_args__ case Point(x, y):
write most of these for you @dataclass see data containers

Python looks special methods up on the class, not the instance. Each table reads: method → triggered by → example.

Method Triggered by Example
__new__(cls, *args) Cls(...), first; creates and returns the object subclass str, int, tuple; instance caching
__init__(self, *args) Cls(...), after __new__; fills the object; returns None self.cents = cents
__del__(self) garbage collection; timing not guaranteed rarely; use with for cleanup
__copy__(self) copy.copy(x) share or reset caches
__deepcopy__(self, memo) copy.deepcopy(x) copy nested state
__getstate__(self) pickle.dumps(x), copy drop an open file or lock
__setstate__(self, state) pickle.loads(...), copy reopen the resource
__reduce__(self) pickle for objects that need custom rebuilding return (Cls, (self.a,))
__reduce_ex__(self, protocol) pickle, copy; tried before __reduce__ rarely overridden
__getnewargs_ex__(self), __getnewargs__(self) unpickling a class whose __new__ needs arguments return ((self.code,), {})
__post_init__(self) a @dataclass __init__, after the fields are set (not a Python dunder) see data containers
__sizeof__(self) sys.getsizeof(x) shallow size in bytes
Method Triggered by Example
__repr__(self) repr(x), REPL echo, items inside containers, f"{x!r}", f"{x=}", logging %r Money(1349, 'USD')
__str__(self) str(x), print(x); f"{x}" through the default __format__; falls back to __repr__ 13.49 USD
__format__(self, spec) format(x, spec), f"{x:spec}", and f"{x}" with spec '' (the default object.__format__ calls str()) f"{m:.0f}"
__bytes__(self) bytes(x) a binary message
__bool__(self) bool(x), if x:, while x:, and, or, not; falls back to __len__ zero money is falsy
__int__, __float__, __complex__ int(x), float(x), complex(x) float(Money(250)) → 2.5
__index__(self) x as an index or slice bound, range(x), bin(x), hex(x) integer-like IDs
__round__(self, n=None) round(x), round(x, n) round money to cents
__trunc__, __floor__, __ceil__ math.trunc(x), math.floor(x), math.ceil(x) numeric types
__fspath__(self) os.fspath(x), open(x), Path(x) Upload("a.csv") used as a path
Method Triggered by Reflection if NotImplemented Example
__eq__(self, other) a == b, x in list, list.index, list.count, list.remove b.__eq__(a) same fields
__ne__(self, other) a != b; default inverts __eq__ b.__ne__(a) rarely written
__lt__(self, other) a < b, sorted(), list.sort(), min(), max(), heapq, bisect b.__gt__(a) older version
__le__(self, other) a <= b b.__ge__(a) from @total_ordering
__gt__(self, other) a > b b.__lt__(a) from @total_ordering
__ge__(self, other) a >= b b.__le__(a) from @total_ordering
__hash__(self) hash(x), set members, dict keys, functools.cache arguments — hash((self.major, self.minor))
Method Triggered by Example
__len__(self) len(x); truth test when __bool__ is missing len(playlist)
__getitem__(self, key) x[key]; x[a:b] passes a slice; x[i, j] passes a tuple playlist[0], grid[1, 2]
__setitem__(self, key, value) x[key] = value a settings store
__delitem__(self, key) del x[key] a settings store
__missing__(self, key) d[key] on a dict subclass when the key is missing defaultdict, Counter
__contains__(self, item) item in x, item not in x; falls back to __iter__ 21.5 in Range(19, 23)
__reversed__(self) reversed(x); falls back to __len__ + __getitem__ newest first
__length_hint__(self) operator.length_hint(x); list pre-sizing lazy iterators
Method Triggered by Example
__iter__(self) for, list(x), sum(x), zip(), *x, a, b = x, comprehensions yield from self._items
__next__(self) next(it); only on iterators; raise StopIteration at the end generator objects
__aiter__(self) async for item in x a stream of messages
__anext__(self) each step of async for; raise StopAsyncIteration async generators
__await__(self) await x custom awaitables (rare)
Method Triggered by Example
__call__(self, *args) x(...) a stateful callback, a decorator class
__enter__(self) the start of with x as name:; its result goes to name open a transaction
__exit__(self, exc_type, exc, tb) the end of the with block, also after an exception; return True to suppress commit or roll back
__aenter__, __aexit__ async with x: httpx.AsyncClient, DB sessions
Operator Method Reflected (x on the right) In place
a + b __add__ __radd__ a += b → __iadd__
a - b __sub__ __rsub__ __isub__
a * b __mul__ __rmul__ __imul__
a / b __truediv__ __rtruediv__ __itruediv__
a // b __floordiv__ __rfloordiv__ __ifloordiv__
a % b __mod__ __rmod__ __imod__
divmod(a, b) __divmod__ __rdivmod__ —
a ** b, pow(a, b) __pow__ __rpow__ __ipow__
a @ b __matmul__ __rmatmul__ __imatmul__
a & b __and__ __rand__ __iand__
a | b __or__ __ror__ __ior__
a ^ b __xor__ __rxor__ __ixor__
a << b, a >> b __lshift__, __rshift__ __rlshift__, __rrshift__ __ilshift__, __irshift__
Method Triggered by Example
__neg__(self) -x -Vector(1, 2)
__pos__(self) +x rarely; Decimal rounds to context
__abs__(self) abs(x) vector length
__invert__(self) ~x NOT of a pandas mask, a flag set
Method Triggered by Example
__getattr__(self, name) x.name when normal lookup fails delegation proxies, lazy attributes
__getattribute__(self, name) every x.name, before anything else tracing; avoid overriding
__setattr__(self, name, value) x.name = value, setattr() read-only objects, change tracking
__delattr__(self, name) del x.name, delattr() block deletes
__dir__(self) dir(x), tab completion list dynamic attributes
__slots__ (a class attribute) instance creation: fixed attribute names, no __dict__ memory per object
Method Triggered by Example
__get__(self, obj, objtype=None) obj.attr when attr is a descriptor on the class; obj is None for Cls.attr property, methods, cached_property
__set__(self, obj, value) obj.attr = value; makes it a data descriptor that wins over vars(obj) validated fields
__delete__(self, obj) del obj.attr rare
__set_name__(self, owner, name) the owner class is created (after its body runs); tells the descriptor its attribute name self.private = "_" + name
Method Triggered by Example
__init_subclass__(cls, **kwargs) a subclass is created; keywords come from the class line class Csv(Exporter, fmt="csv")
__class_getitem__(cls, item) Cls[item] list[int], Box[str]
__mro_entries__(self, bases) a non-class object listed as a base typing.NamedTuple
__instancecheck__, __subclasscheck__ isinstance(), issubclass(); defined on a metaclass ABCs, Protocols
__subclasshook__(cls, sub) issubclass() on an ABC Sized accepts any class with __len__
__prepare__(name, bases) before the class body runs; on a metaclass enum collects members
__match_args__ (a class attribute) positional class patterns in match case Point(x, y):
__buffer__(self, flags) (3.12+) memoryview(x) binary data without copies
__release_buffer__(self, view) (3.12+) the memoryview is released free or unlock the buffer
Function in a module Triggered by Example
def __getattr__(name) module.name (or from module import name) when the name is missing lazy imports, a DeprecationWarning for an old name
def __dir__() dir(module) list the lazy names
Attribute Holds Example
obj.__dict__ the instance namespace (same as vars(obj)) {'cents': 1349}
obj.__class__ the class of the object (same as type(obj)) Money
Cls.__name__, Cls.__qualname__ the name; the dotted path inside the module 'Inner', 'Outer.Inner'
Cls.__module__ the module that defines it 'billing.money'
x.__doc__ the docstring help(x) shows it
Cls.__mro__, Cls.__bases__ the lookup order; the direct parents see inheritance
x.__annotations__ type hints of a class or a function (prefer typing.get_type_hints(x)) {'cents': <class 'int'>}
func.__wrapped__ the original function under a functools.wraps decorator unwrap for tests
obj.__weakref__ the weak-reference slot needed with __slots__ for weakref.ref(obj)
module.__file__, module.__name__ the file path; '__main__' when run as a script if __name__ == "__main__":
class Money:
def __init__(self, cents: int, currency: str = "USD") -> None:
self.cents, self.currency = cents, currency
def __repr__(self) -> str: # developers: looks like the constructor call
return f"{type(self).__name__}({self.cents!r}, {self.currency!r})"
def __str__(self) -> str: # users: readable
return f"{self.cents / 100:.2f} {self.currency}"
def __format__(self, spec: str) -> str: # f"{m:,.0f}"
return f"{format(self.cents / 100, spec or '.2f')} {self.currency}"
def __bool__(self) -> bool:
return self.cents != 0
m = Money(123456)
print(m, repr(m), [m]) # print -> str; inside containers -> repr
print(f"{m} | {m!r} | {m:,.0f} | {m=}")
print(bool(Money(0)), "free" if not Money(0) else "paid")
Output
1234.56 USD Money(123456, 'USD') [Money(123456, 'USD')]
1234.56 USD | Money(123456, 'USD') | 1,235 USD | m=Money(123456, 'USD')
False free
Rule Why
always write __repr__ str() falls back to it; nothing falls back to __str__
make the repr look like the constructor call you can paste it into code
use !r for fields in a repr strings keep their quotes
use type(self).__name__ subclasses show their own name
keep reprs short for big objects show sizes and keys, not 10,000 rows
a custom __format__ must handle an empty spec plain f"{x}" calls it with ''
without __format__ f"{x:>10}" raises TypeError: unsupported format string passed to X.__format__
from functools import total_ordering
@total_ordering # writes <=, > and >= from __eq__ and __lt__
class Version:
def __init__(self, text: str) -> None:
self.parts = tuple(int(p) for p in text.split("."))
def __repr__(self) -> str:
return f"Version({'.'.join(map(str, self.parts))!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Version):
return NotImplemented # not False: let the other side answer
return self.parts == other.parts
def __lt__(self, other: object) -> bool:
if not isinstance(other, Version):
return NotImplemented
return self.parts < other.parts
def __hash__(self) -> int: # the same fields as __eq__
return hash(self.parts)
vs = [Version(t) for t in ["1.10.0", "1.9.3", "1.9.3", "2.0"]]
print(sorted(set(vs)), max(vs), Version("1.10") >= Version("1.9"))
print(Version("1.0") == "1.0", Version("1.0") in vs)
Output
[Version('1.9.3'), Version('1.10.0'), Version('2.0')] Version('2.0') True
False False
Class defines == means __hash__ Hashable?
neither identity (is) identity-based yes
__eq__ only your rule set to None no: TypeError: unhashable type
__eq__ and __hash__ your rule your rule yes, if the fields never change
__hash__ = None inherited None no (says so on purpose)

The hash contract: a == b implies hash(a) == hash(b). Hash only fields that never change. @total_ordering needs __eq__ and one of __lt__, __le__, __gt__, __ge__; it does not check that they agree.

from collections.abc import Iterator
class Playlist:
def __init__(self, songs: list[str]) -> None:
self._songs = list(songs)
def __repr__(self) -> str:
return f"Playlist({self._songs!r})"
def __len__(self) -> int:
return len(self._songs)
def __getitem__(self, key: int | slice) -> "str | Playlist":
if isinstance(key, slice):
return type(self)(self._songs[key]) # a slice keeps the class
return self._songs[key] # IndexError comes from the list
def __iter__(self) -> Iterator[str]:
yield from self._songs # a fresh iterator for each loop
def __contains__(self, song: object) -> bool:
return isinstance(song, str) and song.lower() in (s.lower() for s in self)
p = Playlist(["Intro", "Song A", "Song B", "Outro"])
print(len(p), p[0], p[-1], p[1:3], "song a" in p)
print(list(reversed(p)), [s.upper() for s in p][:2], bool(p[4:]))
first, *rest = p
print(first, rest)
Output
4 Intro Outro Playlist(['Song A', 'Song B']) True
['Outro', 'Song B', 'Song A', 'Intro'] ['INTRO', 'SONG A'] False
Intro ['Song A', 'Song B', 'Outro']
Missing method Python falls back to
__iter__ __getitem__(0), (1), … until IndexError
__contains__ a loop over __iter__ with ==
__bool__ __len__() != 0; with neither, always True
__reversed__ __len__ + __getitem__ from the end
__ne__ not __eq__
__radd__ etc. TypeError: unsupported operand type(s)

For a full container, subclass collections.abc.Sequence or Mapping and write only the abstract methods (see ABC vs Protocol).

class CallCounter:
def __init__(self, func) -> None: # a decorator written as a class
self.func, self.calls = func, 0
def __call__(self, *args, **kwargs):
self.calls += 1
return self.func(*args, **kwargs)
@CallCounter
def slugify(text: str) -> str:
return text.strip().lower().replace(" ", "-")
class Transaction:
def __init__(self, store: dict[str, int]) -> None:
self.store = store
def __enter__(self) -> dict[str, int]:
self._backup = dict(self.store) # snapshot
return self.store # bound to the name after "as"
def __exit__(self, exc_type, exc, tb) -> bool:
if exc_type is not None: # an error in the block: roll back
self.store.clear()
self.store.update(self._backup)
print("rolled back:", exc)
return False # do not suppress the exception
print(slugify("Hello World"), slugify(" Python "), slugify.calls, callable(slugify))
accounts = {"ada": 100, "bob": 0}
try:
with Transaction(accounts) as acc:
acc["ada"] -= 30
acc["bob"] += 30
raise RuntimeError("network down")
except RuntimeError:
pass
print(accounts)
Output
hello-world python 2 True
rolled back: network down
{'ada': 100, 'bob': 0}
__exit__ returns Effect
None or False an exception from the block propagates after cleanup
True the exception is suppressed (use with care)

__exit__ does not run if __enter__ raises. For simple cases, @contextlib.contextmanager with try/finally around a yield is shorter.

Operators: arithmetic, reflected, in place

Section titled “Operators: arithmetic, reflected, in place”
import math
class Vector:
def __init__(self, *xs: float) -> None:
self.xs = tuple(xs)
def __repr__(self) -> str:
return f"Vector{self.xs}"
def __add__(self, other: object) -> "Vector":
if not isinstance(other, Vector):
return NotImplemented
return Vector(*(a + b for a, b in zip(self.xs, other.xs, strict=True)))
def __radd__(self, other: object) -> "Vector":
return self if other == 0 else self.__add__(other) # sum() starts at 0
def __mul__(self, k: object) -> "Vector":
if isinstance(k, bool) or not isinstance(k, (int, float)):
return NotImplemented
return Vector(*(a * k for a in self.xs))
__rmul__ = __mul__ # 2 * v: commutative, share the method
def __neg__(self) -> "Vector":
return self * -1
def __abs__(self) -> float:
return math.hypot(*self.xs)
class Total: # a mutable accumulator: in-place operator returns self
def __init__(self) -> None:
self.value = 0.0
def __iadd__(self, x: float) -> "Total":
self.value += x
return self
v, w = Vector(3, 4), Vector(1, 1)
print(v + w, 2 * v, -w, abs(v), sum([v, w, w]))
t = Total()
t += 2.5
t += 1
print(t.value)
try:
print(v + 1)
except TypeError as err:
print(err)
Output
Vector(4, 5) Vector(6, 8) Vector(-1, -1) 5.0 Vector(5, 6)
3.5
unsupported operand type(s) for +: 'Vector' and 'int'

How Python evaluates a + b:

  1. If type(b) is a subclass of type(a) and overrides __radd__, try b.__radd__(a) first.
  2. Otherwise call a.__add__(b). Any result except NotImplemented is the answer.
  3. Then try b.__radd__(a).
  4. If both return NotImplemented or are missing: TypeError: unsupported operand type(s) for +.

a += b tries a.__iadd__(b) first, then falls back to a = a + b. Immutable types (int, str, tuple) have no __iadd__, so += builds a new object.

class Proxy:
def __init__(self, target: object) -> None:
self._target = target
self.calls: list[str] = []
def __getattr__(self, name: str) -> object: # only for names not found normally
if name.startswith("__"): # copy and pickle probe dunders before __init__
raise AttributeError(name)
self.calls.append(name)
return getattr(vars(self)["_target"], name) # delegate; no recursion
class ReadOnly:
def __init__(self, **fields: object) -> None:
for k, v in fields.items():
object.__setattr__(self, k, v) # bypass our own __setattr__
def __setattr__(self, name: str, value: object) -> None:
raise AttributeError(f"{type(self).__name__} is read-only: cannot set {name!r}")
p = Proxy("Hello")
print(p.upper(), p.startswith("He"), p.calls) # p.calls itself is found normally
cfg = ReadOnly(host="localhost", port=8000)
try:
cfg.port = 9000
except AttributeError as err:
print(err, cfg.port)
Output
HELLO True ['upper', 'startswith']
ReadOnly is read-only: cannot set 'port' 8000
Rule Why
prefer __getattr__ to __getattribute__ __getattr__ runs only for missing names
inside __getattribute__, call object.__getattribute__(self, name) self.x there recurses forever
inside __setattr__, write with object.__setattr__ or super().__setattr__ self.x = v there recurses forever
raise AttributeError for unknown names hasattr() and getattr(obj, n, default) rely on it
guard __getattr__ for copy and pickle they build the object without __init__; reading self._target there recurses
special methods bypass __getattr__ len(proxy) does not delegate; define __len__ explicitly

A descriptor is an object in a class body that controls access to one attribute. property, methods, classmethod, staticmethod and cached_property are all descriptors. Write your own to reuse one check on many attributes.

class Positive:
def __set_name__(self, owner: type, name: str) -> None: # runs at class creation
self.public, self.private = name, "_" + name
def __get__(self, obj: object, objtype: type | None = None) -> object:
if obj is None: # accessed on the class: return the descriptor itself
return self
return getattr(obj, self.private)
def __set__(self, obj: object, value: float) -> None: # data descriptor
if value <= 0:
raise ValueError(f"{self.public} must be > 0, got {value}")
setattr(obj, self.private, value)
class Order:
price = Positive() # one line per validated attribute
quantity = Positive()
def __init__(self, price: float, quantity: int) -> None:
self.price = price # runs Positive.__set__
self.quantity = quantity
o = Order(9.99, 3)
print(o.price, o.quantity, sorted(vars(o)), type(Order.price).__name__)
try:
o.quantity = 0
except ValueError as err:
print(err)
Output
9.99 3 ['_price', '_quantity'] Positive
quantity must be > 0, got 0
Kind Defines Precedence
data descriptor __get__ and __set__ (or __delete__) wins over vars(obj): property, Positive
non-data descriptor __get__ only vars(obj) wins: functions, cached_property (that is how it caches)
from typing import ClassVar
class Exporter:
registry: ClassVar[dict[str, type["Exporter"]]] = {}
def __init_subclass__(cls, *, fmt: str, **kwargs: object) -> None:
super().__init_subclass__(**kwargs)
Exporter.registry[fmt] = cls # runs once per subclass, at class creation
class CsvExporter(Exporter, fmt="csv"):
pass
class JsonExporter(Exporter, fmt="json"):
pass
class Box:
def __class_getitem__(cls, item: object) -> str: # Box[int]
return f"{cls.__name__}[{getattr(item, '__name__', item)}]"
print({k: v.__name__ for k, v in Exporter.registry.items()}, Box[int], list[int])
Output
{'csv': 'CsvExporter', 'json': 'JsonExporter'} Box[int] list[int]

In real code, write class Box[T]: (3.12+) or subclass typing.Generic[T] instead of a hand-written __class_getitem__.

  • Special methods on the instance. Symptom: obj.__len__ = lambda: 3 does not change len(obj). Fix: define it on the class.
  • __eq__ without __hash__. Symptom: TypeError: unhashable type in a set or as a dict key. Fix: add __hash__ over the same fields, or use @dataclass(frozen=True).
  • Hashing mutable fields. Symptom: an object “disappears” from a set after a change. Fix: hash only fields that never change.
  • NotImplementedError instead of NotImplemented. Symptom: a == b raises instead of returning False. Fix: return NotImplemented (a value), never raise it.
  • return False for unknown types in __eq__. Symptom: the other operand never gets a say. Fix: return NotImplemented.
  • print([x]) ignores __str__. Symptom: a list shows reprs. Fix: that is by design; write a good __repr__.
  • Wrong return types. Symptom: TypeError from len() or bool(). Fix: __len__ returns an int ≥ 0, __bool__ a bool, __repr__ a str.
  • __iter__ returns self without __next__. Symptom: TypeError: iter() returned non-iterator. Fix: write __iter__ as a generator.
  • One-shot iterator. Symptom: a second loop over the object is empty. Fix: return a fresh iterator from __iter__ on each call.
  • Slices return a plain list. Symptom: obj[1:3].method() fails. Fix: check isinstance(key, slice) and return type(self)(...).
  • sum() of custom objects. Symptom: TypeError: unsupported operand type(s) for +: 'int' and 'X'. Fix: __radd__ that accepts 0, or sum(xs, start=zero).
  • __exit__ returns True by accident. Symptom: every error in the with block vanishes. Fix: return None or False.
  • Recursion in __setattr__ or __getattribute__. Symptom: RecursionError. Fix: use object.__setattr__ / object.__getattribute__.
  • __getattr__ hides typos. Symptom: a misspelled attribute returns something instead of failing. Fix: raise AttributeError for names you do not handle.
  • __del__ for cleanup. Symptom: files or connections stay open. Fix: use a context manager.
  • Surprising operators. Symptom: readers cannot guess what pipeline + model does. Fix: overload only operators with an obvious meaning; use named methods otherwise.

Python has many ways to hold a record such as a user, an order or a config. This page shows when to use each one, then the options of @dataclass and __slots__.

I want to… Use… Example
a record class without boilerplate @dataclass @dataclass class User: name: str
a default value name: type = value retries: int = 3
a fresh list or dict per instance field(default_factory=list) tags: list[str] = field(default_factory=list)
validate or normalize after __init__ __post_init__ if self.port < 1: raise ValueError(...)
a field computed from others field(init=False) + __post_init__ total: float = field(init=False)
an argument only for __post_init__ InitVar[T] password: InitVar[str]
read-only, hashable instances @dataclass(frozen=True) dict keys, cache keys, settings
set a field in a frozen __post_init__ object.__setattr__(self, name, value)
sort instances by their fields @dataclass(order=True) fields compared as a tuple, in order
leave a field out of == and sorting field(compare=False) a cache, a timestamp
hide a secret in the repr field(repr=False) api_key: str = field(repr=False)
force keyword arguments kw_only=True, KW_ONLY, field(kw_only=True) Config(debug=True)
forbid new attributes and save memory @dataclass(slots=True) typos raise AttributeError
copy with changes (also frozen) dataclasses.replace(obj, **changes) replace(cfg, debug=True)
convert to a dict or tuple (recursive) asdict(obj), astuple(obj) json.dumps(asdict(order))
list the fields dataclasses.fields(obj_or_cls) [f.name for f in fields(User)]
check “is this a dataclass” dataclasses.is_dataclass(x)
a tuple with field names typing.NamedTuple lat, lon = point
copy a named tuple with a change nt._replace(field=value)
a named tuple without type hints (older code) collections.namedtuple("Point", "x y", defaults=[0]) Point(1) → Point(x=1, y=0)
type hints for JSON dicts passed on unchanged TypedDict class Payload(TypedDict): id: int
optional keys in a TypedDict NotRequired[T] nickname: NotRequired[str]
validate and convert untrusted input a pydantic BaseModel User.model_validate(request_json)
fixed attributes in a plain class __slots__ = ("x", "y") no __dict__
a quick throwaway object with attributes types.SimpleNamespace(a=1) test doubles, parsed args
a read-only view of a dict types.MappingProxyType(d) expose config without copying
a fixed set of named options Enum see enums
Need Use Why
quick script, keys not known in advance dict no class needed
JSON in, JSON out, light processing dict + TypedDict hints stays a dict; mypy checks keys
a small result that callers unpack NamedTuple name, score = best
a record with defaults, methods, light validation @dataclass standard library, readable, typed
a value that must not change, a dict key @dataclass(frozen=True) or NamedTuple hashable
millions of small records in memory @dataclass(slots=True) or NamedTuple no per-object __dict__
an object with behavior and changing state plain class a client, a service, a model
untrusted input (HTTP body, config file, CLI) that must be validated and converted pydantic BaseModel type coercion, clear errors, JSON schema
a table of many rows a pandas or Polars DataFrame columns, not objects
dict TypedDict NamedTuple @dataclass plain class pydantic BaseModel
Access d["k"] d["k"] t.k, t[0] o.k o.k m.k
Type hints no yes (checker only) yes yes by hand yes, enforced
Run-time validation no no no __post_init__ by hand by hand yes, automatic
Converts types ("7" → 7) no no no no by hand yes (lax mode)
Mutable yes yes no yes (or frozen=True) yes yes (or frozen=True)
Hashable no no yes with frozen=True by identity with frozen=True
Unpacks like a tuple no no yes no no no
Equals plain data — equals a dict equals a tuple no no no
__init__, __repr__, __eq__ built-in built-in generated generated by hand generated
To dict / JSON it is one it is one _asdict() asdict() by hand model_dump(), model_dump_json()
Dependency none none none none none pydantic
from dataclasses import asdict, dataclass
from typing import NamedTuple, TypedDict
from pydantic import BaseModel, ValidationError
raw = {"id": "7", "email": "ADA@example.com"} # e.g. a JSON request body
class UserDict(TypedDict):
id: int
email: str
class UserTuple(NamedTuple):
id: int
email: str
@dataclass
class UserData:
id: int
email: str
def __post_init__(self) -> None:
self.email = self.email.lower() # normalize by hand
class UserModel(BaseModel):
id: int
email: str
td: UserDict = {"id": 7, "email": "ada@example.com"} # a plain dict at run time
nt = UserTuple(7, "ada@example.com")
dc = UserData(int(raw["id"]), raw["email"]) # you convert the types yourself
pm = UserModel.model_validate(raw) # pydantic converts "7" -> 7
print(type(td).__name__, nt, nt == (7, "ada@example.com"))
print(dc, asdict(dc))
print(repr(pm), pm.model_dump())
print(UserData("7", "x").id == 7) # annotations are not checked
try:
UserModel.model_validate({"id": "seven", "email": "x"})
except ValidationError as err:
first = err.errors()[0]
print(err.error_count(), first["loc"], first["type"])
Output
dict UserTuple(id=7, email='ada@example.com') True
UserData(id=7, email='ada@example.com') {'id': 7, 'email': 'ada@example.com'}
UserModel(id=7, email='ADA@example.com') {'id': 7, 'email': 'ADA@example.com'}
False
1 ('id',) int_parsing
Parameter Default Effect
init True generate __init__
repr True generate __repr__ (fields with repr=True)
eq True generate __eq__: compares fields as a tuple, only with the same class
order False generate <, <=, >, >=; needs eq=True
frozen False assignment raises FrozenInstanceError; with eq=True, generates __hash__
unsafe_hash False generate __hash__ even when not frozen
match_args True generate __match_args__ for case User(name, age):
kw_only False every field is keyword-only
slots False generate __slots__ (returns a new class)
weakref_slot False add a __weakref__ slot (with slots=True)
Options __eq__ __hash__ Set member / dict key
@dataclass by fields None no
frozen=True by fields by fields yes
eq=False identity identity yes, by identity
unsafe_hash=True by fields by fields yes, if you never change the fields

A method you write yourself, such as __repr__, is kept: @dataclass adds only what is missing. With order=True, also writing __lt__ raises TypeError.

Argument Default Effect
default none the default value
default_factory none a zero-argument callable called for each new instance: list, dict, lambda: [0]
init True a parameter of __init__; False for computed fields
repr True shown in __repr__
compare True used by __eq__, the order methods and the hash
hash None None follows compare; False leaves it out of the hash
kw_only MISSING True: keyword-only parameter
metadata None a read-only mapping for your own tools (fields(cls)[0].metadata)
Special annotation Meaning
x: ClassVar[int] = 0 a class attribute, not a field
x: InitVar[str] an __init__ argument passed to __post_init__, not stored
_: KW_ONLY every field below is keyword-only
no annotation (x = 0) a plain class attribute, not a field
import json
from dataclasses import KW_ONLY, asdict, dataclass, field, fields, replace
@dataclass
class Order:
id: str
items: list[str] = field(default_factory=list) # one list per order
price: float = 0.0
total: float = field(init=False) # computed, not an __init__ parameter
_: KW_ONLY # everything below is keyword-only
currency: str = "USD"
note: str = field(default="", repr=False, compare=False)
def __post_init__(self) -> None: # validate and derive after __init__
if self.price < 0:
raise ValueError(f"price must be >= 0, got {self.price}")
self.total = round(len(self.items) * self.price, 2)
o = Order("A-1", ["pen", "ink"], 2.5, currency="EUR", note="hi")
print(o) # note has repr=False
print(json.dumps(asdict(o))) # asdict() includes every field
print([f.name for f in fields(o)])
print(o == Order("A-1", ["pen", "ink"], 2.5, currency="EUR")) # note not compared
o2 = replace(o, price=3.0) # a new object; __post_init__ runs again
print(o2.total, o2.items is o.items) # replace() is shallow: the list is shared
Output
Order(id='A-1', items=['pen', 'ink'], price=2.5, total=5.0, currency='EUR')
{"id": "A-1", "items": ["pen", "ink"], "price": 2.5, "total": 5.0, "currency": "EUR", "note": "hi"}
['id', 'items', 'price', 'total', 'currency', 'note']
True
6.0 True
from dataclasses import FrozenInstanceError
@dataclass(frozen=True, order=True, slots=True)
class Version:
major: int
minor: int = 0
label: str = field(default="", compare=False) # not part of ==, < or the hash
v = Version(1, 10, "lts")
print([(x.major, x.minor) for x in sorted([Version(2), v, Version(1, 9)])])
print(v, v == Version(1, 10))
print({v: "supported"}[Version(1, 10)], hasattr(v, "__dict__"))
try:
v.major = 3
except FrozenInstanceError as err:
print(type(err).__name__, err)
match v:
case Version(1, minor): # positional pattern from __match_args__
print("1.x line, minor", minor)
Output
[(1, 9), (1, 10), (2, 0)]
Version(major=1, minor=10, label='lts') True
supported False
FrozenInstanceError cannot assign to field 'major'
1.x line, minor 10
Task Code
a required field after defaults make it keyword-only: field(kw_only=True) or kw_only=True
validate types for real __post_init__ with isinstance, or use pydantic
frozen with a derived field object.__setattr__(self, "slug", ...) in __post_init__
an immutable default in a frozen class tags: tuple[str, ...] = ()
inherit from a dataclass @dataclass class Admin(User): level: int = 1; fields append in order
build from a dict User(**data); unknown keys raise TypeError
build from a dict with extra keys User(**{f.name: data[f.name] for f in fields(User) if f.name in data})
print a long dataclass readably pprint.pprint(obj)
a dataclass in a pydantic model allowed: pydantic validates standard dataclasses as fields
from typing import NamedTuple, NotRequired, TypedDict
class Point(NamedTuple):
lat: float
lon: float
label: str = "" # defaults come last
class Event(TypedDict):
name: str
user_id: int
source: NotRequired[str] # the key may be missing
p = Point(48.86, 2.35, "Paris")
lat, lon, _ = p # unpacks like a tuple
print(p.lat, p[1], p._replace(label="FR"))
print(p._asdict())
e: Event = {"name": "login", "user_id": 7}
print(e.get("source", "web"), Point._fields, sorted([Point(2, 0), Point(1, 9)])[0])
Output
48.86 2.35 Point(lat=48.86, lon=2.35, label='FR')
{'lat': 48.86, 'lon': 2.35, 'label': 'Paris'}
web ('lat', 'lon', 'label') Point(lat=1, lon=9, label='')
class Plain:
def __init__(self, x: float, y: float) -> None:
self.x, self.y = x, y
class Slotted:
__slots__ = ("x", "y") # fixed attribute names; no __dict__
def __init__(self, x: float, y: float) -> None:
self.x, self.y = x, y
s = Slotted(1.0, 2.0)
try:
s.z = 3.0 # a typo or a new attribute
except AttributeError as err:
print(type(err).__name__, "for 'z'") # the message text differs by version
print(hasattr(Plain(1, 2), "__dict__"), hasattr(s, "__dict__"))
print(vars(Plain(1, 2)), Slotted.__slots__)
Output
AttributeError for 'z'
True False
{'x': 1, 'y': 2} ('x', 'y')
Rule Detail
saves the per-object __dict__; measure with tracemalloc before you optimize
forbids new attributes and vars(obj)
unset slot reading it raises AttributeError
class attribute with a slot’s name ValueError: 'x' in __slots__ conflicts with class variable
subclass without __slots__ gets a __dict__ again
subclass with __slots__ lists only its new names
multiple inheritance at most one base may have non-empty slots
cached_property needs a __dict__: fails on slotted classes
@dataclass(slots=True) handles defaults for you; zero-argument super() in its methods fails on 3.12–3.13
does not freeze values combine with frozen=True for that
  • Mutable default. Symptom: items: list = [] raises ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory. Fix: field(default_factory=list).
  • Field order. Symptom: TypeError: non-default argument 'b' follows default argument 'a'. Fix: put required fields first, or make later fields keyword-only.
  • Annotations are not checked. Symptom: User(id="7") stores a string. Fix: convert in __post_init__, or use pydantic for untrusted input.
  • No annotation, no field. Symptom: x = 0 in a dataclass is missing from __init__ and asdict(). Fix: annotate it: x: int = 0.
  • __post_init__ runs once. Symptom: later assignments skip the validation. Fix: use frozen=True, or a property or descriptor for that field.
  • frozen=True is shallow. Symptom: a list field still changes, and hash() fails because lists are unhashable. Fix: store tuples and frozensets.
  • replace() shares mutable fields. Symptom: changing the copy’s list changes the original. Fix: pass a new list: replace(o, items=list(o.items)).
  • asdict() deep-copies and keeps enum members. Symptom: slow on big nested objects; json.dumps() fails for a plain Enum. Fix: use StrEnum or convert .value; write a custom to_dict() for hot paths.
  • compare=False also removes the field from the hash. Symptom: two objects with different labels are equal. Fix: that is intended; keep identity fields compared.
  • order=True sorts by field order. Symptom: records sort by the first field, not the one you meant. Fix: put the sort key first, or use sorted(key=...).
  • NamedTuple equals a plain tuple. Symptom: Point(1, 2) == (1, 2) is True, and two different named tuples with the same values are equal. Fix: use a frozen dataclass when the type matters.
  • TypedDict is only for the type checker. Symptom: missing or wrong keys pass at run time. Fix: validate with pydantic’s TypeAdapter or by hand.
  • dict everywhere. Symptom: KeyError: 'emial' deep in the code. Fix: turn the record into a dataclass at the boundary.
  • __slots__ with a class-level default. Symptom: ValueError: ... conflicts with class variable. Fix: set defaults in __init__, or use @dataclass(slots=True).

An enum is a class with a fixed set of named members, such as order states, log levels or HTTP methods. Enums replace “magic strings” and “magic numbers”: a typo becomes an error, and editors can autocomplete the choices.

I want to… Use… Example
name a fixed set of choices class Status(Enum): Status.PAID
members that are real strings StrEnum Method.GET == "GET"
members that are real, ordered ints IntEnum Priority.HIGH > Priority.LOW
combinable on/off options Flag (or IntFlag) Perm.READ | Perm.WRITE
choose values automatically auto() Enum: 1, 2, 3; StrEnum: lowercase name; Flag: 1, 2, 4
look up a member by value Status("paid") ValueError if unknown
look up a member by name Status["PAID"] KeyError if unknown
look up safely Status.__members__.get(name) or try/except ValueError None if unknown
accept messy input (case, spaces) a _missing_ class method Status(" PAID ")
test a value (3.12+) "paid" in Status True
test a member Status.PAID in Status True
get the name and the value .name, .value 'PAID', 'paid'
list all members list(Status), for s in Status definition order, no aliases
count the members len(Status)
map names to members, aliases included Status.__members__ a read-only mapping
compare members is (members are singletons) if s is Status.PAID:
branch on a member match s: / case Status.PAID: dotted names only
add behavior to members methods and properties in the enum Status.PAID.is_final
attach several values to a member a tuple value + __init__ PLANET = (mass, radius)
forbid duplicate values @enum.unique ValueError at class creation
check unique or gap-free values @enum.verify(UNIQUE, CONTINUOUS) ValueError: invalid enum 'C': missing values 2
keep a constant in an enum that is not a member LIMIT = enum.nonmember(10) Status.LIMIT is 10, not in list(Status)
create an enum from a list the functional API Enum("Color", ["RED", "GREEN"])
store in JSON or a database .value, or a StrEnum / IntEnum json.dumps(s.value)
restrict CLI choices choices=[s.value for s in Status] argparse
validate API input an enum field in pydantic status: Status
standard-library enums http.HTTPStatus, http.HTTPMethod, signal.Signals, re.RegexFlag HTTPStatus.NOT_FOUND.value → 404
from enum import Enum, unique
@unique # duplicate values would raise ValueError here
class Status(Enum):
PENDING = "pending"
PAID = "paid"
SHIPPED = "shipped"
CANCELLED = "cancelled"
@property
def is_final(self) -> bool: # behavior lives with the choices
return self in (Status.SHIPPED, Status.CANCELLED)
@classmethod
def open_states(cls) -> list["Status"]:
return [s for s in cls if not s.is_final]
s = Status("paid") # by value
print(s, repr(s), s.name, s.value, Status["PAID"] is s) # by name; singletons
print([m.value for m in Status], len(Status), "paid" in Status, "PAID" in Status)
print(s.is_final, Status.SHIPPED.is_final, [m.name for m in Status.open_states()])
print(s == "paid", s.value == "paid", f"{s}", f"{s.value}")
Output
Status.PAID <Status.PAID: 'paid'> PAID paid True
['pending', 'paid', 'shipped', 'cancelled'] 4 True False
False True ['PENDING', 'PAID']
False True Status.PAID paid
Operation Result Unknown input
Status("paid") member by value ValueError: 'x' is not a valid Status
Status["PAID"] member by name KeyError: 'x'
getattr(Status, "PAID") member by name AttributeError
"paid" in Status (3.12+) is it a value? False
Status.PAID.name, .value 'PAID', 'paid' —
list(Status) members in definition order, aliases skipped —
Status.__members__ name → member, aliases included —
Status.PAID is Status("paid") True: one object per member —
Status.PAID = "x" AttributeError: members are read-only —
Status.PAID < Status.SHIPPED TypeError for a plain Enum use IntEnum or define __lt__

A second name with an existing value is an alias: DONE = "shipped" in the class body makes Status.DONE is Status.SHIPPED. @unique forbids aliases.

import json
from enum import Flag, IntEnum, StrEnum, auto
class Method(StrEnum):
GET = auto() # auto() in a StrEnum: the lowercase name
POST = auto()
class Priority(IntEnum):
LOW = 1
NORMAL = 2
HIGH = 3
class Perm(Flag):
READ = auto() # 1
WRITE = auto() # 2
DELETE = auto() # 4
ADMIN = READ | WRITE | DELETE # a named combination
print(Method.GET, Method.GET == "get", Method.POST.upper(), json.dumps([Method.GET]))
print(Priority.HIGH > Priority.LOW, Priority.NORMAL + 1, max(Priority).name)
print(sorted([Priority.HIGH, Priority.LOW]), Priority(2).name, f"{Priority.LOW}")
user = Perm.READ | Perm.WRITE
print(user, Perm.WRITE in user, Perm.DELETE in user, Perm.READ in Perm.ADMIN)
print(user & ~Perm.WRITE, bool(Perm(0)), [p.name for p in user], Perm.ADMIN.value)
Output
get True POST ["get"]
True 3 HIGH
[<Priority.LOW: 1>, <Priority.HIGH: 3>] NORMAL 1
Perm.READ|WRITE True False True
Perm.READ False ['READ', 'WRITE'] 7
Enum StrEnum (3.11+) IntEnum Flag IntFlag
Member is a member only str int member, combinable int, combinable
member == value False True True False True
< between members TypeError as strings as ints TypeError as ints
str(member) / f-string Status.PAID get (the value) 1 (the value) Perm.READ 1
json.dumps(member) TypeError the value the value TypeError the value
auto() values 1, 2, 3 lowercase name 1, 2, 3 1, 2, 4, 8 1, 2, 4, 8
Use for states, kinds, modes HTTP methods, config keys, DB codes priorities, levels, status codes permissions, feature sets OS flags, re flags
Stdlib example uuid.SafeUUID http.HTTPMethod http.HTTPStatus your own permission sets re.RegexFlag, ssl.VerifyFlags
Code Value
A = auto() in Enum / IntEnum 1, 2, 3, … (highest int value so far + 1, on 3.13+)
A = auto() in StrEnum "a" (lowercase name)
A = auto() in Flag / IntFlag 1, 2, 4, 8, …
_generate_next_value_(name, start, count, last_values) your rule for auto(); define it first in the class (a static method)
A = "text" any value; mix literals with auto() only when they are ints (Enum, IntEnum) or strings (StrEnum)
MARS = (6.4e23, 3.39e6) + def __init__(self, mass, radius) several attributes per member; .value is the tuple
from enum import Enum
class Plan(Enum):
FREE = ("free", 0)
PRO = ("pro", 1200) # (code, price in cents)
def __init__(self, code: str, cents: int) -> None: # runs once per member
self.code = code
self.cents = cents
@property
def label(self) -> str:
return f"{self.name.title()} ({self.cents / 100:.2f} USD/month)"
print(Plan.PRO.code, Plan.PRO.cents, Plan.PRO.label, Plan(("free", 0)).name)
Output
pro 1200 Pro (12.00 USD/month) FREE
from enum import StrEnum
class Env(StrEnum):
DEV = "dev"
STAGING = "staging"
PROD = "prod"
@classmethod
def _missing_(cls, value: object) -> "Env | None": # called when lookup fails
aliases = {"development": "dev", "production": "prod"}
if isinstance(value, str):
key = value.strip().lower()
key = aliases.get(key, key)
for member in cls:
if member.value == key:
return member
return None # None: Python raises the usual ValueError
print(Env(" PROD "), Env("Development"), Env("staging"))
try:
Env("qa")
except ValueError as err:
print(err)
Output
prod dev staging
'qa' is not a valid Env

_missing_ runs only for value lookup, Env(...). Name lookup, Env["..."], never calls it.

from enum import Enum, auto
class Shape(Enum):
CIRCLE = auto()
SQUARE = auto()
TRIANGLE = auto()
def corners(shape: Shape) -> int:
match shape:
case Shape.CIRCLE: # a dotted name: a value pattern, compared with ==
return 0
case Shape.SQUARE:
return 4
case Shape.TRIANGLE:
return 3
case _: # fail loudly if a member is added and not handled
raise ValueError(f"unhandled {shape!r}")
def kind(value: object) -> str:
match value:
case Shape.CIRCLE | Shape.SQUARE: # OR pattern
return "regular"
case Shape(): # class pattern: any other Shape member
return "other shape"
case _:
return "not a shape"
print([corners(s) for s in Shape], kind(Shape.SQUARE), kind(Shape.TRIANGLE), kind(3))
Output
[0, 4, 3] regular other shape not a shape
Pattern Means
case Shape.CIRCLE: value pattern: == Shape.CIRCLE
case CIRCLE: capture pattern: binds any value to the name CIRCLE and always matches
case Shape.CIRCLE | Shape.SQUARE: either member
case Shape(): any member of Shape
case "get": on a StrEnum member matches, because the member equals the string

mypy and pyright warn when a match on an enum misses a member, if you end with case _: assert_never(shape) (from typing import assert_never).

Task Code
to JSON json.dumps({"status": s.value}); a StrEnum / IntEnum works directly
from JSON Status(data["status"])
from a config or env var Env(os.environ.get("APP_ENV", "dev"))
an argparse option parser.add_argument("--env", type=Env, choices=list(Env))
a pydantic field status: Status; the input "paid" becomes Status.PAID
a database column store .value; SQLAlchemy has Enum(Status)
a dataclass field status: Status = Status.PENDING; asdict() keeps the member
a dict keyed by member {Status.PAID: "green", Status.CANCELLED: "red"}; members are hashable
a pandas column df["status"].map(lambda v: Status(v).name), or a categorical with the values
import json
from enum import Enum
class Color(Enum):
RED = "red"
BLUE = "blue"
Level = Enum("Level", ["DEBUG", "INFO", "ERROR"]) # functional API: values 1, 2, 3
payload = json.dumps({"color": Color.RED.value})
print(payload, Color(json.loads(payload)["color"]), Level.INFO.value, Level(3).name)
try:
json.dumps({"color": Color.RED})
except TypeError as err:
print(err)
Output
{"color": "red"} Color.RED 2 ERROR
Object of type Color is not JSON serializable
  • A plain Enum member is not its value. Symptom: Status.PAID == "paid" is False. Fix: compare with .value, convert input with Status(value), or use StrEnum.
  • StrEnum and IntEnum equal their values. Symptom: mix-ups such as Priority.HIGH == 3 and Priority.HIGH + 1 pass silently. Fix: use a plain Enum when members must not act like numbers or strings.
  • str() differs by kind. Symptom: an f-string shows Status.PAID for Enum but paid for StrEnum and 1 for IntEnum. Fix: write .value or .name explicitly in output.
  • auto() in a StrEnum uses the lowercase name. Symptom: MONTH_TO_MONTH = auto() gives "month_to_month", not "month-to-month". Fix: write the value explicitly when it must match external data.
  • Capture pattern in match. Symptom: case PAID: binds any value to the name PAID and always matches: a SyntaxError when other cases follow, a silent catch-all when it is last. Fix: write case Status.PAID:.
  • json.dumps() of a plain Enum. Symptom: TypeError: Object of type Color is not JSON serializable. Fix: dump .value, or use StrEnum.
  • Aliases hide in iteration. Symptom: list(Status) misses a name you defined. Fix: it is an alias of an earlier member; use __members__ or @unique.
  • auto() after a non-int literal. Symptom: A = "x" then B = auto() in a plain Enum raises TypeError: unable to increment 'x'. Fix: give every member an explicit value, or use auto() for all of them.
  • Value vs name lookup. Symptom: Status("PAID") raises ValueError. Fix: Status["PAID"] looks up names; Status("paid") looks up values.
  • Ordering a plain Enum. Symptom: TypeError: '<' not supported between instances of 'Status' and 'Status'. Fix: IntEnum, or sorted(members, key=lambda m: m.value).
  • Mutable or float values. Symptom: a list value cannot be looked up by value quickly, and float values compare inexactly. Fix: use strings, ints or tuples.
  • Subclassing an enum with members. Symptom: TypeError: <enum 'Sub'> cannot extend <enum 'Status'>. Fix: only enums without members can be subclassed; share behavior with a base enum that has no members.

Design patterns are named, reusable answers to common design problems. Many classic patterns need whole class hierarchies in Java or C++; in Python, functions, modules and duck typing make most of them a few lines. Use a pattern when it removes a real problem, not to look “designed”.

I want to… Use… Example
let the caller choose an algorithm strategy: pass a function sorted(rows, key=by_date), retry(fetch, backoff=expo)
choose an algorithm from config text a dict of functions COMPRESSORS["gzip"]
give a strategy settings functools.partial or a callable object partial(expo, base=2)
build an object from a name a factory over a registry dict make_exporter("csv")
let classes add themselves to a registry a registration decorator or __init_subclass__ @register("csv")
build an object in more than one way an alternative constructor Config.from_toml(path)
fix the steps of an algorithm, vary one step template method + hook run() calls self.handle(item)
react to events without editing the emitter observer: a list of callbacks bus.subscribe("order.paid", send_email)
chain processing steps a pipeline of functions for step in steps: x = step(x)
assemble a complex object step by step a builder with chainable methods Request().header(...).json(...).build()
make a foreign object fit your interface an adapter class S3Storage: def get(...) wraps boto3
add behavior around a function a Python decorator @retry(times=3)
add behavior around an object a wrapper object (decorator pattern) CachedStorage(storage)
one shared object for the whole program a module-level object settings = Settings() in config.py
make code testable without network or files dependency injection def sync(*, client=None, now=datetime.now)
collect output in a test inject list.append job(log=lines.append)
accept only what a function uses a small Protocol class SupportsGet(Protocol): ...
undo or queue actions command: functions or partial in a list queue.append(partial(send, user))
dispatch on a value’s type functools.singledispatch @to_json.register
decide whether a pattern is worth it YAGNI, rule of three wait for the second or third real need
Principle Rule Smell Pythonic fix
Single responsibility one reason to change per unit a class that reads files, computes and formats split by job into functions or small classes
Open/closed extend by adding code, not by editing it an if/elif chain on a kind or a type a dict of functions, a registry, a function parameter
Liskov substitution a subclass works wherever its parent works an override that raises NotImplementedError, rejects valid input or changes the meaning keep the contract; compose instead of inheriting
Interface segregation depend only on the methods you use a fat base class; methods that only raise several small Protocols
Dependency inversion high-level code depends on abstractions, not on details hard-coded paths, print(), clients built inside functions inject callables or objects; build them in main()
Term Meaning Goal Test
coupling how much one part depends on another’s details low can I change this part without editing that one?
cohesion how closely a unit’s contents belong together high can I state this unit’s job in one sentence without “and”?
Pattern Problem it solves Pythonic form When not to use
Strategy swap an algorithm a function parameter only one algorithm exists
Factory / registry build objects by name, from config a dict of classes + a function the caller already knows the class: call it
Template method fixed steps, one varying step a base class whose method calls a hook a function parameter (strategy) is enough
Observer many listeners, one event a list of callables one listener: call it directly
Builder assemble an object step by step, with checks chainable methods that return self keyword arguments or a dataclass do it
Pipeline apply steps in order a list of functions; generators two fixed steps: call them
Adapter make a foreign API fit yours a small wrapper class you own both sides: change one
Decorator (pattern) add behavior around an object a wrapper with the same methods a Python decorator on a function is enough
Singleton one shared instance a module-level object it hides state that tests must reset; inject it
Dependency injection swap real parts for fakes parameters with defaults the dependency never varies and is pure
Command queue, log or undo actions a function, a partial, a dataclass a direct call works
import math
from collections.abc import Callable
from functools import partial
type Backoff = Callable[[int], float] # attempt number -> seconds to wait
def constant(attempt: int, delay: float = 1.0) -> float:
return delay
def exponential(attempt: int, base: float = 2.0, cap: float = 30.0) -> float:
return min(cap, base**attempt)
BACKOFFS: dict[str, Backoff] = {"constant": constant, "exponential": exponential}
def schedule(retries: int, backoff: Backoff) -> list[float]: # the context
return [backoff(i) for i in range(retries)]
print(schedule(4, constant), schedule(4, BACKOFFS["exponential"]))
print(schedule(4, partial(exponential, base=3, cap=10)), schedule(3, math.sqrt))
Output
[1.0, 1.0, 1.0, 1.0] [1.0, 2.0, 4.0, 8.0]
[1, 3, 9, 10] [0.0, 1.0, 1.4142135623730951]
Form When
a function no settings: key=len, backoff=constant
partial or a closure settings fixed once
a callable object (__call__) settings to show in a repr or change later, or state
a name in a dict the choice comes from text: config, CLI, a form

When not to use: one algorithm and no plan for a second. Write backoff=exponential() by mistake and you call it: a TypeError here, or a number instead of a function.

from collections.abc import Callable
from typing import Any
EXPORTERS: dict[str, type] = {}
def register(name: str) -> Callable[[type], type]:
def decorator(cls: type) -> type:
if name in EXPORTERS:
raise ValueError(f"exporter {name!r} is already registered")
EXPORTERS[name] = cls
return cls # return the class unchanged
return decorator
def make_exporter(name: str, **options: Any) -> Any: # the factory
try:
cls = EXPORTERS[name]
except KeyError:
known = sorted(EXPORTERS)
raise ValueError(f"unknown exporter {name!r}; choose from {known}") from None
return cls(**options) # a fresh object on every call
@register("csv")
class CsvExporter:
def __init__(self, sep: str = ",") -> None:
self.sep = sep
def export(self, rows: list[list[object]]) -> str:
return "\n".join(self.sep.join(map(str, r)) for r in rows)
@register("tsv")
class TsvExporter(CsvExporter):
def __init__(self) -> None:
super().__init__(sep="\t")
print(repr(make_exporter("tsv").export([["id", "total"], [1, 9.5]])))
try:
make_exporter("xml")
except ValueError as err:
print(err)
Output
'id\ttotal\n1\t9.5'
unknown exporter 'xml'; choose from ['csv', 'tsv']
  • A class registers when its module is imported. Import every plugin module (for example in the package __init__.py), or the name is “unknown”.
  • Register classes, not instances: an instance would be shared by every caller.
  • Plugins from other packages: entry points in pyproject.toml and importlib.metadata.entry_points(group="myapp.exporters").

When not to use: one product, or the caller always knows the class. Then CsvExporter() is the factory.

from abc import ABC, abstractmethod
class Job(ABC):
def run(self, items: list[str]) -> list[str]: # the template: fixed steps
results = []
for item in items:
if not item.strip(): # shared validation
continue
results.append(self.handle(item.strip())) # the hook
return self.finish(results)
@abstractmethod
def handle(self, item: str) -> str: ... # required hook
def finish(self, results: list[str]) -> list[str]: # optional hook: a default
return results
class SlugJob(Job):
def handle(self, item: str) -> str:
return item.lower().replace(" ", "-")
def finish(self, results: list[str]) -> list[str]:
return sorted(results)
print(SlugJob().run(["Hello World", " ", "About Us"]))
Output
['about-us', 'hello-world']

Template methods you already use: unittest.TestCase (setUp, test, tearDown), threading.Thread.run, logging.Handler.emit, http.server.BaseHTTPRequestHandler.do_GET, Django class-based views, PyTorch nn.Module.forward.

When not to use: the only variation is one function. Pass it as a parameter (strategy) instead of making a class hierarchy. Never override the template itself (run) in a subclass: it loses the shared steps.

from collections import defaultdict
from collections.abc import Callable
type Handler = Callable[[dict[str, object]], None]
class EventBus: # the subject
def __init__(self) -> None:
self._handlers: defaultdict[str, list[Handler]] = defaultdict(list)
def subscribe(self, event: str, handler: Handler) -> None:
self._handlers[event].append(handler)
def publish(self, event: str, payload: dict[str, object]) -> None:
for handler in self._handlers[event]: # the subject knows nothing else
handler(payload)
bus = EventBus()
sent: list[str] = []
bus.subscribe("order.paid", lambda p: sent.append(f"email {p['user']}"))
bus.subscribe("order.paid", lambda p: sent.append(f"invoice {p['order_id']}"))
bus.publish("order.paid", {"user": "ada", "order_id": "A-1"})
bus.publish("order.refunded", {"user": "bob"}) # no subscribers: nothing happens
print(sent)
Output
['email ada', 'invoice A-1']
Form When
a list of functions one event: on_save=[log, notify]
a dict of event name → handlers an event bus with several events
a base class with empty on_* methods several events; each observer overrides only some (training callbacks)
a flag on the subject an observer must change the flow (stop, skip)

When not to use: a single listener (call it), or when the order and failures of handlers matter (a handler that raises stops the others; make that explicit).

from typing import Self
from urllib.parse import urlencode
class RequestBuilder:
def __init__(self, url: str) -> None:
self._url = url
self._headers: dict[str, str] = {}
self._params: dict[str, str] = {}
def header(self, name: str, value: str) -> Self:
self._headers[name] = value
return self # a fluent interface: calls chain
def param(self, name: str, value: object) -> Self:
self._params[name] = str(value)
return self
def build(self) -> dict[str, object]:
if not self._url.startswith("https://"): # check once, at the end
raise ValueError("only https URLs are allowed")
query = urlencode(self._params) # escapes &, = and spaces
url = f"{self._url}?{query}" if query else self._url
return {"url": url, "headers": dict(self._headers)}
req = (
RequestBuilder("https://api.example.com/orders")
.param("page", 2)
.param("limit", 50)
.header("Accept", "application/json")
.build()
)
print(req["url"], req["headers"])
steps = [str.strip, str.lower, lambda s: " ".join(s.split())] # a pipeline
text = " Wireless EARBUDS "
for step in steps:
text = step(text) # each output is the next input
print(repr(text))
Output
https://api.example.com/orders?page=2&limit=50 {'Accept': 'application/json'}
'wireless earbuds'
Choose When
keyword arguments or a dataclass all parts are known at the call site (most cases)
a builder parts are added in a loop, from config, or optionally, and need checks
a pipeline of functions each step has the same shape: data in, data out
generator chains streams too big for memory: clean(parse(read(path)))
scikit-learn Pipeline, pandas .pipe() data-science steps with fit / transform

When not to use a builder: Request(url, headers={...}, params={...}) already reads well. A builder for three optional arguments is ceremony.

class LegacyMailer: # third-party code you cannot change
def deliver(self, recipient_list: list[str], body_text: str) -> int:
return len(recipient_list)
class Notifier: # the interface your code expects: notify(user, message)
def __init__(self, mailer: LegacyMailer) -> None:
self._mailer = mailer
def notify(self, user: str, message: str) -> bool:
return self._mailer.deliver([f"{user}@example.com"], message) == 1
print(Notifier(LegacyMailer()).notify("ada", "Your order shipped"))
Output
True

Adapters keep a third-party API at the edge of your code: when the library changes, only the adapter changes. Tests replace the adapter with a fake.

When not to use: you own both sides (rename the method), or the wrapper only forwards every call unchanged.

Decorator pattern Python decorator (@)
Wraps an object, keeping its interface a function or a class, at definition time
Chosen at run time: Logged(Cached(storage)) when the code is written: @cache
Form a class with the same methods that holds the inner object a function that takes and returns a function
Examples io.BufferedReader(raw), gzip.GzipFile(fileobj=f) @functools.cache, @retry, @app.get("/")
import functools
from collections.abc import Callable
class DictStorage:
def __init__(self) -> None:
self.data = {"a": "1"}
self.reads = 0
def get(self, key: str) -> str | None:
self.reads += 1
return self.data.get(key)
class CachedStorage: # decorator pattern: same get(), adds caching
def __init__(self, inner: DictStorage) -> None:
self._inner = inner
self._cache: dict[str, str | None] = {}
def get(self, key: str) -> str | None:
if key not in self._cache:
self._cache[key] = self._inner.get(key)
return self._cache[key]
def logged[**P, R](func: Callable[P, R]) -> Callable[P, R]: # a Python decorator
@functools.wraps(func) # keep the name and the docstring
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
result = func(*args, **kwargs)
print(f"{func.__name__}{args} -> {result!r}")
return result
return wrapper
@logged
def add(a: int, b: int) -> int:
return a + b
raw = DictStorage()
store = CachedStorage(raw)
print(store.get("a"), store.get("a"), store.get("z"), raw.reads)
add(2, 3)
Output
1 1 None 2
add(2, 3) -> 5

When not to use the pattern: a function decorator already does it, or the wrapper must forward dozens of methods (consider __getattr__ delegation or subclassing instead).

# config.py: the module is the singleton; Python imports it once per process
import os
from dataclasses import dataclass
@dataclass(frozen=True)
class Settings:
database_url: str
debug: bool = False
settings = Settings(
database_url=os.environ.get("DATABASE_URL", "sqlite:///dev.db"),
debug=os.environ.get("DEBUG") == "1",
)
# elsewhere:
# from config import settings
# connect(settings.database_url)
Need Python form
one shared configuration a module-level object
one lazily built expensive object @functools.cache on a zero-argument function: get_client()
one instance per class, enforced rarely needed; a __new__ that caches is possible but surprising
reset between tests inject the object, or call get_client.cache_clear()

When not to use: a global that functions read implicitly makes tests depend on each other. Pass the object as a parameter wherever you can; keep the module-level object for main() and the framework entry points.

from collections.abc import Callable
from datetime import UTC, datetime
type Fetch = Callable[[str], list[dict[str, object]]]
def daily_report(
*,
fetch: Fetch, # required dependency
now: Callable[[], datetime] = lambda: datetime.now(UTC), # default: the real clock
log: Callable[[str], None] = print, # default: the console
) -> int:
orders = fetch("/orders?status=paid")
stamp = now().date().isoformat()
log(f"{stamp}: {len(orders)} paid orders")
return len(orders)
lines: list[str] = []
count = daily_report(
fetch=lambda path: [{"id": 1}, {"id": 2}], # a fake API client
now=lambda: datetime(2024, 5, 1, tzinfo=UTC), # a fixed clock
log=lines.append, # capture the output
)
print(count, lines)
Output
2 ['2024-05-01: 2 paid orders']
Form Example
a parameter with a production default def job(*, log=print)
a constructor argument UserService(repo=SqlRepo(engine))
a factory from config make_exporter(config["format"])
a composition root main() builds the real clients and passes them down
framework support FastAPI Depends(get_db), pytest fixtures

When not to use: pure functions with no I/O need nothing injected. Prefer injection to monkeypatch when you own the code; patching depends on how the function is written inside.

Pattern Classic form Python form
Strategy an interface + one class per algorithm a function; key=, backoff=
Command an object with execute() a function or a partial; a dataclass for undo data
Factory method / abstract factory creator class hierarchies a function, a @classmethod, a dict of classes
Singleton a private constructor + instance() a module-level object, or @functools.cache
Iterator hasNext() / next() classes __iter__ and generators
Decorator a wrapper class per behavior a function decorator or a wrapper object
Adapter a wrapper class the same; or a few functions
Observer subject and observer interfaces a list of callables
Template method an abstract class with hooks the same: ABC + @abstractmethod
Visitor double dispatch functools.singledispatch or match
Builder director + builder classes keyword arguments, dataclasses; a fluent builder for step-by-step assembly
Prototype clone() methods copy.copy(), copy.deepcopy(), dataclasses.replace()
Proxy a class with the same interface __getattr__ delegation
Sign Simpler
a class with __init__ and one method a function
an abstract base class with one subclass no base; add it at the second subclass
a factory with one product call the class
getters and setters attributes; @property when a check is needed
a wrapper that only forwards calls call the inner object
config options nobody sets delete them (YAGNI: “you aren’t gonna need it”)
the third copy of a block now extract it (rule of three)
a singleton class a module-level object

A class earns its place when it keeps state between calls (a client with a session, a model with learned parameters) or groups several operations on the same data.

Pattern Standard library Web and tools Data science
Strategy sorted(key=), re.sub(func), json.dumps(default=) Django password hashers, auth backends metric=, scoring=
Factory / registry codecs.lookup, logging.getLogger Flask @app.route, pytest plugins, entry points get_scorer("r2")
Template method unittest.TestCase, Thread.run, logging.Handler.emit Django class-based views TransformerMixin.fit_transform (calls your fit and transform), nn.Module.forward
Observer logging handlers, atexit.register Django signals, Qt signals, webhooks Keras / Lightning callbacks
Pipeline generator chains, itertools middleware, Unix pipes scikit-learn Pipeline, .pipe()
Builder argparse.ArgumentParser.add_argument SQLAlchemy select().where(), Django QuerySet.filter().order_by() Polars lazy queries
Adapter io.TextIOWrapper database drivers behind DB-API pandas readers
Decorator functools.cache, contextlib.contextmanager @app.get, @login_required @torch.no_grad()
Dependency injection default parameters FastAPI Depends, pytest fixtures random_state=, injected loaders
  • Calling the strategy. Symptom: backoff=exponential() raises a TypeError or passes a number. Fix: pass the function itself: backoff=exponential.
  • Registry not filled. Symptom: “unknown exporter” for a class you wrote. Fix: the module with @register must be imported first.
  • Silent overwrite in a registry. Symptom: two classes under one name; the last one wins. Fix: raise on duplicates in the decorator.
  • Shared instance in a registry or default argument. Symptom: state leaks between callers. Fix: store classes or factories; build fresh objects.
  • Overriding the template. Symptom: a subclass skips validation or logging. Fix: override the hook, not the template method.
  • A hook that calls the template. Symptom: RecursionError. Fix: hooks do one step only.
  • Observer failures. Symptom: one handler raises and the rest never run. Fix: decide on purpose: catch and log per handler, or let it propagate.
  • Observers that keep state. Symptom: the second run reports the first run’s data. Fix: reset state in a start event, or create a fresh observer per run.
  • Builder without return self. Symptom: AttributeError: 'NoneType' object has no attribute 'header'. Fix: every chain method returns self.
  • Hidden globals. Symptom: tests pass alone and fail together. Fix: inject the dependency; reset module-level caches in fixtures.
  • Decorator without functools.wraps. Symptom: every function is named wrapper in logs and tracebacks. Fix: add @functools.wraps(func).
  • Lambdas in configs. Symptom: a strategy cannot be saved as JSON or pickled. Fix: store a name and resolve it with a dict.
  • Pattern for its own sake. Symptom: an interface, a factory and a builder for one class. Fix: write the simplest code; refactor when the second real case arrives.

NumPy gives Python fast n-dimensional arrays of one dtype. This page is a reference for NumPy 2.x: how to build, index, combine and reduce arrays, and the rules that cause most bugs (dtype promotion, views, broadcasting). Every block runs in order and shares the setup below.

import numpy as np
np.set_printoptions(precision=3, suppress=True) # display only; values unchanged
m = np.arange(12).reshape(3, 4) # a small 3 x 4 integer matrix
temps = np.array([20.2, 22.3, np.nan, 24.5, 38.0])
I want to… Use… Example
make an array from a list np.array(seq, dtype=...) np.array([1, 2], dtype=np.float32)
wrap data without a copy if possible np.asarray(x) accepts lists, arrays, pandas columns
make evenly spaced numbers np.arange, np.linspace np.linspace(0, 1, 5)
make a filled array np.zeros, np.ones, np.full, *_like np.full((2, 3), np.nan)
make a coordinate grid np.meshgrid(x, y), np.indices xx, yy = np.meshgrid(x, y)
see the size and type .shape, .ndim, .size, .dtype, .nbytes m.shape → (3, 4)
convert the dtype a.astype(dtype) a.astype(np.int32)
predict a result dtype np.result_type(a, b) np.result_type(np.int8, np.uint8)
take a row, column or block a[i], a[:, j], a[r0:r1, c0:c1] m[:, 1]
keep values that pass a test a boolean mask a[(a > 0) & (a < 9)]
pick rows in a given order fancy indexing m[[2, 0]]
pick a block from row and column lists np.ix_(rows, cols) m[np.ix_([0, 2], [1, 3])]
check if two arrays share memory np.shares_memory(a, b) views share, copies do not
get an independent copy a.copy() before you edit a slice
combine shapes (n, 1) and (1, k) broadcasting col[:, None] * row
keep a reduced axis keepdims=True a / a.sum(axis=1, keepdims=True)
sum per column / per row axis=0 / axis=1 m.sum(axis=0)
find the position of the max argmax, then np.unravel_index np.unravel_index(m.argmax(), m.shape)
ignore NaN in a statistic np.nanmean, np.nanmax, … np.nanmean(temps)
vectorized if/else np.where(cond, a, b) np.where(t > 30, "hot", "ok")
vectorized if/elif/else np.select(conds, choices, default) first true condition wins
put values into bins np.digitize(x, edges) np.digitize(t, [25, 35])
sort, or get the sort order np.sort, np.argsort np.argsort(-x)[:3]
top k without a full sort np.argpartition np.argpartition(x, -3)[-3:]
distinct values and counts np.unique(a, return_counts=True)
test membership np.isin(a, values) replaces np.in1d
change the shape .reshape, .ravel, .T a.reshape(-1, 4)
add or drop a length-1 axis a[:, None], np.expand_dims, np.squeeze
join arrays np.concatenate, np.stack, np.column_stack np.stack([a, b], axis=1)
split an array np.split, np.array_split np.array_split(a, 3)
matrix product A @ B * is element-wise
solve Ax = b np.linalg.solve(A, b) not inv(A) @ b
fit a least-squares line np.linalg.lstsq(X, y) coef = lstsq(X, y)[0]
eigenvalues of a symmetric matrix np.linalg.eigh(S) real, ascending
reproducible random numbers rng = np.random.default_rng(42) rng.normal(0, 1, 3)
compare float arrays np.allclose, np.isclose not ==
compare arrays exactly np.array_equal(a, b, equal_nan=True)
get plain Python values .item(), .tolist(), float(x) for JSON and clean printing
save and load arrays np.save, np.load, np.savez_compressed .npy keeps shape and dtype
Call Result Note
np.array([[1, 2], [3, 4]]) 2 × 2 int64 nested lists → axes
np.array([1, 2.5]) float64 one float upcasts all
np.asarray(x) x itself if already a matching array no copy when possible
np.zeros((2, 3)), np.ones(3) float64 0.0 / 1.0 pass dtype= for others
np.full(shape, value) filled with a value np.full(3, np.nan)
np.empty(n) uninitialized memory fill it before you read it
np.zeros_like(a), np.full_like(a, 7) same shape and dtype as a
np.arange(start, stop, step) stop excluded float steps can miss the end
np.linspace(a, b, n) n points, both ends included endpoint=False to drop b
np.logspace(0, 3, 4) 1, 10, 100, 1000 log-scale grids
np.eye(n), np.identity(n) identity matrix
np.diag(v) / np.diag(M) diagonal matrix / the diagonal
np.tile(a, reps), np.repeat(a, k) repeat the whole / each element
np.meshgrid(x, y) 2-D coordinate arrays indexing="ij" for matrix order
np.fromfunction(f, shape) f(i, j) for every index f gets whole index arrays
print(np.arange(0, 1, 0.25), np.linspace(0, 1, 5))
print(np.tile([1, 2], 2), np.repeat([1, 2], 2))
xx, yy = np.meshgrid(np.arange(3), np.arange(2)) # xx varies along columns
print(xx, yy, sep="\n")
print(np.fromfunction(lambda i, j: i * 10 + j, (2, 3), dtype=int))
print(m.shape, m.ndim, m.size, m.dtype, m.itemsize, m.nbytes, len(m))
Output
[0. 0.25 0.5 0.75] [0. 0.25 0.5 0.75 1. ]
[1 2 1 2] [1 1 2 2]
[[0 1 2]
[0 1 2]]
[[0 0 0]
[1 1 1]]
[[ 0 1 2]
[10 11 12]]
(3, 4) 2 12 int64 8 96 3
dtype Bytes Range / precision Typical use
bool 1 True / False masks; sum() counts True
int8 / uint8 1 −128..127 / 0..255 images, small codes
int16 / int32 2 / 4 ±32,767 / ±2.1 × 10⁹ compact integers
int64 8 ±9.2 × 10¹⁸ default integer (Linux, macOS, Windows on NumPy 2)
float32 4 ~7 significant digits deep learning, GPU
float64 8 ~15–17 significant digits default float
complex128 16 two float64 FFT, eig results
<U10 40 text up to 10 characters 4 bytes per character
datetime64[D], timedelta64[s] 8 dates, durations np.datetime64("2024-05-01")
object 8 any Python object slow, avoid

NumPy 2 decides the result dtype from the dtypes, never from the values. Python int, float and complex are “weak”: they take the array’s dtype when the kind fits. NumPy scalars such as np.float64(1) are “strong” and count like arrays.

Expression Result dtype Why
int8_array + 5 int8 weak Python int takes the array dtype
int8_array + 300 OverflowError 300 does not fit int8
int8_array + 5.0 float64 a Python float with an int array → default float
float32_array * 2.0 float32 weak Python float keeps float32
float32_array + np.float64(1) float64 NumPy 2 change: NumPy scalars are strong (was float32)
int8_array + int16_array int16 smallest type that holds both
int8_array + uint8_array int16 signed and unsigned → wider signed
int64_array + float32_array float64 float32 cannot hold every int64
int_array / int_array float64 true division; // stays integer
np.float32(3) + 3.0 float32 scalar with weak Python float
i8 = np.array([100, 120], dtype=np.int8)
f32 = np.array([1.5], dtype=np.float32)
print((i8 + 5).dtype, (i8 + 5.0).dtype, (f32 * 2.0).dtype, (f32 + np.float64(1)).dtype)
print(i8 + i8) # wraps around silently
print(i8.astype(np.int64) + i8) # upcast first
print(np.result_type(np.int8, np.uint8), np.result_type(np.int64, np.float32))
print(np.iinfo(np.int8).max, np.finfo(np.float32).eps)
print(np.array([2.7, -2.7]).astype(int)) # truncates toward zero
print(np.round([0.5, 1.5, 2.5])) # rounds half to even
print(np.can_cast(np.int64, np.float64), np.can_cast(np.float64, np.int64))
Output
int8 float64 float32 float64
[-56 -16]
[200 240]
int16 float64
127 1.1920929e-07
[ 2 -2]
[0. 2. 2.]
True False
bad = np.array([1, 2], dtype=np.int8) + 300 # the Python int does not fit int8
Output
OverflowError: Python integer 300 out of bounds for int8
Helper Does
a.astype(t) always a new array (pass copy=False to skip a no-op copy)
np.result_type(*arrays_or_dtypes) the dtype an operation would give
np.can_cast(from, to) is the cast “safe” (no loss)?
np.iinfo(t), np.finfo(t) integer limits; float eps, max, tiny
np.isdtype(t, "real floating") dtype kind test ("integral", "numeric", "bool")
np.issubdtype(a.dtype, np.floating) older kind test, still valid
Index Shape from (3, 4) Returns
a[1, 2] () one element (a NumPy scalar)
a[1], a[1, :] (4,) a row, view
a[:, 2] (3,) a column, view
a[:, 2:3], a[:, [2]] (3, 1) a column that keeps its axis
a[:2, 1:] (2, 3) a block, view
a[::-1], a[:, ::2] (3, 4), (3, 2) reversed, every second, view
a[..., 0] (3,) ... means all earlier axes
a[:, None, :], a[:, np.newaxis] (3, 1, 4) a new length-1 axis, view
a[a > 5] (n,) a boolean mask, 1-D copy
a[[2, 0]] (2, 4) fancy indexing, copy
a[[0, 2], [1, 3]] (2,) pairs (0, 1) and (2, 3), copy
a[np.ix_([0, 2], [1, 3])] (2, 2) the block of those rows and columns
print(m[1, 2], m[-1, -1], m[1], m[:, 2])
print(m[:2, 1:])
print(m[m % 5 == 0], m[[2, 0], 0], m[[0, 2], [1, 3]])
print(m[np.ix_([0, 2], [1, 3])])
t = np.array([22.0, 34.0, 25.0, 43.0])
print(t[(t > 24) & (t < 40)], t[~(t > 30)], np.isin(t, [25.0, 43.0]))
print(np.nonzero(t > 30), np.flatnonzero(m > 9), np.argwhere(m > 9).tolist())
Output
6 11 [4 5 6 7] [ 2 6 10]
[[1 2 3]
[5 6 7]]
[ 0 5 10] [8 0] [ 1 11]
[[ 1 3]
[ 9 11]]
[34. 25.] [22. 25.] [False False True True]
(array([1, 3]),) [10 11] [[2, 2], [2, 3]]

Assignment works through every index kind and changes the array in place:

g = np.zeros((3, 4), dtype=int)
g[0] = 1 # broadcast a scalar to a row
g[:, -1] = [7, 8, 9] # a column from a list
g[g == 0] = -1 # a mask
g[[1, 2], [0, 1]] = 5 # two single cells
print(g)
counts = np.zeros(3, dtype=int)
idx = np.array([0, 0, 2])
counts[idx] += 1 # buffered: index 0 counts once
print(counts, np.bincount(idx, minlength=3))
np.add.at(counts, idx, 1) # unbuffered: every repeat counts
print(counts)
Output
[[ 1 1 1 7]
[ 5 -1 -1 8]
[-1 5 -1 9]]
[1 0 1] [2 0 1]
[3 0 2]

A view is a new array object over the same memory. Writing to a view changes the original.

Gives a view Gives a copy
basic slices a[1:3], a[:, 0], a[::2] boolean masks a[mask]
a.T, a.transpose(), a.swapaxes() fancy indexing a[[0, 2]]
a.reshape(...) when the memory layout allows a.copy(), np.array(a)
a.ravel() on contiguous data a.flatten()
a[:, None], np.expand_dims, np.squeeze a.astype(t)
a.view(dtype) every arithmetic result a + 1, np.sqrt(a)
row = m[0] # view
picked = m[[0]] # copy
print(np.shares_memory(row, m), np.shares_memory(picked, m), row.base is not None)
work = m.copy()
work[0, 0] = 99 # m is unchanged
print(m[0, 0], work[0, 0], m.T.flags["C_CONTIGUOUS"], m.flags["C_CONTIGUOUS"])
Output
True False True
0 99 False True

NumPy 2 copy= keyword on np.array, np.asarray, astype and reshape:

copy= Meaning
True always copy
None (default of asarray, reshape) copy only when needed
False never copy; raise ValueError if a copy is needed (NumPy 1 meant “copy if needed”)

Two shapes are compatible when, compared from the right, each pair of sizes is equal or one of them is 1. A missing axis counts as 1. The result takes the larger size of each pair.

A B Result Use
(3, 4) () (3, 4) a scalar everywhere
(3, 4) (4,) (3, 4) one value per column
(3, 4) (3, 1) (3, 4) one value per row
(3, 1) (1, 4) (3, 4) an outer table
(n, 1, d) (1, k, d) (n, k, d) all pairwise differences
(3, 4) (3,) error right-aligned: 4 vs 3
col_means = m.mean(axis=0) # (4,)
print(m - col_means) # (3, 4) - (4,)
print((m / m.sum(axis=1, keepdims=True)).round(2)) # row shares: (3, 4) / (3, 1)
print(np.arange(3)[:, None] * np.arange(4)) # (3, 1) * (4,) -> (3, 4)
pts = np.array([[0.0, 0.0], [3.0, 4.0], [6.0, 8.0]])
d = np.sqrt(((pts[:, None, :] - pts[None, :, :]) ** 2).sum(axis=-1))
print(d) # pairwise distances (3, 3)
print(np.broadcast_shapes((5, 1, 4), (3, 1)))
Output
[[-4. -4. -4. -4.]
[ 0. 0. 0. 0.]
[ 4. 4. 4. 4.]]
[[0. 0.17 0.33 0.5 ]
[0.18 0.23 0.27 0.32]
[0.21 0.24 0.26 0.29]]
[[0 0 0 0]
[0 1 2 3]
[0 2 4 6]]
[[ 0. 5. 10.]
[ 5. 0. 5.]
[10. 5. 0.]]
(5, 3, 4)
bad = m - m.sum(axis=1) # (3, 4) - (3,): compare 4 with 3 on the right
Output
ValueError: operands could not be broadcast together with shapes (3,4) (3,)

A ufunc runs element by element in compiled code and broadcasts its inputs.

Kind Functions
arithmetic + - * / // % **, np.add, np.subtract, np.multiply, np.divide, np.power, np.mod
math np.sqrt, np.exp, np.log, np.log1p, np.expm1, np.log10, np.abs, np.sign
trigonometry np.sin, np.cos, np.arctan2(y, x), np.deg2rad, np.hypot
rounding np.round(a, 2), np.floor, np.ceil, np.trunc, np.rint
two-array min/max np.maximum(a, b), np.minimum(a, b), np.fmax (ignores NaN)
comparison > >= == !=, np.greater, np.isclose(a, b, rtol, atol)
logic &, |, ^, ~, np.logical_and, np.logical_not
float tests np.isnan, np.isinf, np.isfinite
bits np.left_shift, np.bitwise_and, np.bitwise_count
Ufunc method or argument Does Example
f.reduce(a, axis) fold an axis np.add.reduce(x) = x.sum()
f.accumulate(a) running result np.maximum.accumulate(x): running max
f.outer(a, b) every pair np.multiply.outer(a, b)
f.at(a, idx, b) in place, repeats count np.add.at(counts, idx, 1)
out= write into an existing array np.sqrt(x, out=buf)
where= compute only where True (others keep out) np.log(x, out=z, where=x > 0)
x = np.array([3, 1, 4, 1, 5, 9, 2])
print(np.add.reduce(x), np.add.accumulate(x), np.maximum.accumulate(x))
print(np.multiply.outer([1, 2], [1, 10, 100]))
v = np.array([4.0, 0.0, -1.0, 9.0])
safe = np.zeros_like(v)
np.sqrt(v, out=safe, where=v > 0) # no warning for 0 or negatives
print(safe, np.diff(x), np.cumprod([1, 2, 3, 4]))
with np.errstate(divide="ignore"): # silence one known warning locally
print(np.log(np.array([1.0, 0.0])))
Output
25 [ 3 4 8 9 14 23 25] [3 3 4 4 5 9 9]
[[ 1 10 100]
[ 2 20 200]]
[2. 0. 0. 3.] [-2 3 -3 4 4 -7] [ 1 2 6 24]
[ 0. -inf]

The named axis disappears. axis=0 collapses the rows and gives one result per column. axis=1 collapses the columns and gives one result per row.

Call Shape from (2, 3, 4)
a.sum() scalar
a.sum(axis=0) (3, 4)
a.sum(axis=-1) (2, 3)
a.sum(axis=(0, 1)) (4,)
a.sum(axis=1, keepdims=True) (2, 1, 4)
Function Note
sum, prod, mean, median, min, max np.median is a function, not a method
std, var ddof=0 (population) by default; pandas uses ddof=1
argmin, argmax the first position; flat index unless axis=
cumsum, cumprod, np.cumulative_sum(include_initial=True) running totals
np.percentile(a, q), np.quantile(a, q) q in 0–100 / 0–1; method="linear" default
any, all, np.count_nonzero for boolean arrays
np.ptp(a) max − min (the method a.ptp() was removed)
np.average(a, weights=w) a weighted mean
np.histogram(a, bins) counts and edges
np.corrcoef(X, rowvar=False), np.cov(...) columns as variables
print(m.sum(), m.sum(axis=0), m.sum(axis=1), m.mean(axis=1))
print(m.max(axis=0), m.argmax(axis=1), np.unravel_index(m.argmax(), m.shape))
print(m.cumsum(axis=1)[1], np.percentile(m, [25, 50, 75]), np.median(m))
print(round(float(m.std()), 3), round(float(m.std(ddof=1)), 3))
print(np.average([1.0, 2.0, 3.0], weights=[3, 1, 0]), np.ptp(m, axis=1))
counts, edges = np.histogram([1, 2, 2, 3, 8], bins=[0, 2, 4, 10])
print(counts, edges)
Output
66 [12 15 18 21] [ 6 22 38] [1.5 5.5 9.5]
[ 8 9 10 11] [3 3 3] (np.int64(2), np.int64(3))
[ 4 9 15 22] [2.75 5.5 8.25] 5.5
3.452 3.606
1.25 [3 3 3]
[1 3 1] [ 0 2 4 10]

NaN (“not a number”) is a float value. One NaN makes sum, mean and max NaN. An integer array cannot hold NaN.

Plain NaN-aware
sum, prod, cumsum, cumprod np.nansum, np.nanprod, np.nancumsum, np.nancumprod (NaN as 0 or 1)
mean, median, std, var np.nanmean, np.nanmedian, np.nanstd, np.nanvar
min, max, argmin, argmax np.nanmin, np.nanmax, np.nanargmin, np.nanargmax
percentile, quantile np.nanpercentile, np.nanquantile
print(temps.mean(), np.nanmean(temps), np.nanmedian(temps), np.nanargmax(temps))
print(np.isnan(temps).sum(), np.nan == np.nan, np.isnan(np.nan))
print(np.where(np.isnan(temps), np.nanmedian(temps), temps)) # fill with the median
print(temps[~np.isnan(temps)], np.nan_to_num(temps, nan=0.0))
print(np.array_equal(temps, temps), np.array_equal(temps, temps, equal_nan=True))
Output
nan 26.25 23.4 4
1 False True
[20.2 22.3 23.4 24.5 38. ]
[20.2 22.3 24.5 38. ] [20.2 22.3 0. 24.5 38. ]
False True
v = np.array([2.1, 5.0, 12.3, np.nan])
t = np.array([22.0, 34.0, 25.0, 43.0])
status = np.select([(v >= 11.2) | (t >= 42), (v >= 4.5) | (t >= 33)],
["fail", "warn"], default="ok")
print(status, np.where(t > 30, "hot", "ok"))
print(np.clip(t, 20, 35), np.digitize(t, [25, 35]))
print(np.digitize(t, [25, 35], right=True)) # edges[i-1] < x <= edges[i]
Output
['ok' 'warn' 'fail' 'fail'] ['ok' 'hot' 'ok' 'hot']
[22. 34. 25. 35.] [0 1 1 2]
[0 1 0 2]
Function Does
np.where(cond, a, b) element-wise if/else; both a and b are computed
np.where(cond) positions of True (same as np.nonzero)
np.select(conds, choices, default) if/elif/else; the first true condition wins
np.piecewise(x, conds, funcs) a different function per region
np.clip(a, lo, hi) cap values
np.digitize(x, edges) bin number: edges[i-1] <= x < edges[i]
x = np.array([30, 10, 50, 20, 50])
print(np.sort(x), np.argsort(x, stable=True), np.sort(x)[::-1])
print(np.argpartition(x, -2)[-2:], np.searchsorted([10, 20, 30], [15, 30]))
vals, first, inv, cnt = np.unique(x, return_index=True, return_inverse=True,
return_counts=True)
print(vals, first, inv, cnt)
print(np.intersect1d([1, 2, 3], [2, 3, 4]), np.union1d([1, 2], [2, 5]),
np.setdiff1d([1, 2, 3], [2]))
print(np.sort(m[:, ::-1], axis=1)[0], np.lexsort(([2, 1, 1], [0, 1, 0])))
Output
[10 20 30 50 50] [1 3 0 2 4] [50 50 30 20 10]
[2 4] [1 2]
[10 20 30 50] [1 3 0 2] [2 0 3 1 3] [1 1 1 2]
[2 3] [1 2 5] [1 3]
[0 1 2 3] [2 0 1]
  • np.lexsort((secondary, primary)) sorts by the last key first.
  • np.unique returns sorted values. NumPy 2 adds np.unique_values, np.unique_counts, np.unique_inverse and np.unique_all.
flat = np.arange(24)
grid = flat.reshape(4, 6)
print(grid.shape, flat.reshape(2, 3, -1).shape, grid.T.shape) # -1 is inferred
a, b = np.array([1, 2, 3]), np.array([4, 5, 6])
print(np.concatenate([a, b]), np.stack([a, b]).shape, np.stack([a, b], axis=1).shape)
print(np.vstack([a, b]).shape, np.hstack([a, b]).shape, np.column_stack([a, b]).shape)
print(np.concatenate([m, m], axis=1).shape, np.block([[m, m], [m, m]]).shape)
print([p.tolist() for p in np.split(np.arange(6), 3)])
print([len(p) for p in np.array_split(flat, 5)])
print(m[:, None, :].shape, np.expand_dims(a, 0).shape, np.squeeze(m[:, :1]).shape)
print(np.moveaxis(np.zeros((2, 3, 4)), -1, 0).shape)
print(m.ravel()[:5], m.ravel(order="F")[:5]) # row order vs column order
Output
(4, 6) (2, 3, 4) (6, 4)
[1 2 3 4 5 6] (2, 3) (3, 2)
(2, 3) (6,) (3, 2)
(3, 8) (6, 8)
[[0, 1], [2, 3], [4, 5]]
[5, 5, 5, 5, 4]
(3, 1, 4) (1, 3) (3,)
(4, 2, 3)
[0 1 2 3 4] [0 4 8 1 5]
Function Does
a.reshape(r, -1) new shape, same elements in row (C) order; -1 is inferred
a.ravel() / a.flatten() to 1-D: a view if possible / always a copy
a.T, np.transpose(a, axes), np.moveaxis reorder axes
np.concatenate(seq, axis=0) join along an existing axis
np.stack(seq, axis=0) join along a new axis (shapes must match)
np.vstack, np.hstack, np.column_stack rows; columns; 1-D arrays as columns
np.block([[A, B], [C, D]]) assemble a matrix from blocks
np.split(a, n) / np.array_split(a, n) equal parts (else error) / nearly equal parts
np.split(a, [2, 5]) split before positions 2 and 5
a[:, None], np.expand_dims, np.squeeze add or drop length-1 axes
Task Function Note
matrix or dot product A @ B, np.matmul, np.dot * is element-wise
batch of dot products np.vecdot(a, b) (NumPy 2) over the last axis
outer product np.outer(u, v) u[:, None] * v
named-axis products and contractions np.einsum("ij,jk->ik", A, B) "ii->" is the trace
square system Ax = b np.linalg.solve(A, b) LinAlgError if singular
least squares np.linalg.lstsq(X, y) returns coef, residuals, rank, sv
inverse, determinant np.linalg.inv, np.linalg.det rarely needed; prefer solve
symmetric eigen np.linalg.eigh(S) real values, ascending
general eigen np.linalg.eig(M) complex128 on NumPy 2.5, even for real results
SVD np.linalg.svd(M, full_matrices=False) s descending; signs arbitrary
norm, rank, condition np.linalg.norm, matrix_rank, cond large cond: unstable solve
pseudo-inverse np.linalg.pinv(M) for non-square or singular matrices
data = np.genfromtxt("data/houses.csv", delimiter=",", skip_header=1, usecols=(2, 13))
sqft, price = data[:, 0], data[:, 1]
X = np.column_stack([np.ones_like(sqft), sqft]) # design matrix with intercept
coef, *_ = np.linalg.lstsq(X, price)
print(data.shape, coef.round(1))
A = np.array([[3.0, 1.0], [1.0, 2.0]])
b = np.array([9.0, 8.0])
sol = np.linalg.solve(A, b)
print(sol, np.allclose(A @ sol, b), round(float(np.linalg.det(A)), 3))
w, vecs = np.linalg.eigh(A) # symmetric: use eigh
print(w, np.linalg.eig(A).eigenvalues.dtype)
U, s, Vt = np.linalg.svd(m, full_matrices=False)
print(s, np.linalg.matrix_rank(m), np.allclose(U * s @ Vt, m))
print(np.linalg.norm([3.0, 4.0]), np.vecdot(pts, pts))
Output
(3000, 2) [-130345.1 326.8]
[2. 3.] True 5.0
[1.382 3.618] complex128
[22.409 1.955 0. ] 2 True
5.0 [ 0. 25. 100.]

Make one generator with a seed and pass it around. Do not use the legacy global functions (np.random.seed, np.random.rand).

rng = np.random.default_rng(42)
print(rng.normal(0, 1, size=3), rng.integers(1, 7, size=5))
print(rng.random(2), rng.uniform(10, 20, size=2))
print(rng.choice(["a", "b", "c"], size=4, p=[0.5, 0.3, 0.2]))
print(rng.choice(10, 3, replace=False))
print(rng.permutation(5), rng.poisson(4.0, size=3), rng.binomial(10, 0.5, size=3))
same = np.random.default_rng(7).random(3) == np.random.default_rng(7).random(3)
print(same.all(), [int(c.integers(100)) for c in rng.spawn(2)])
Output
[ 0.305 -1.04 0.75 ] [1 5 2 1 4]
[0.761 0.786] [11.281 14.504]
['a' 'c' 'b' 'c']
[9 7 4]
[1 0 4 3 2] [7 1 6] [3 5 4]
True [49, 7]
Legacy (avoid) Generator method
np.random.seed(42) rng = np.random.default_rng(42)
np.random.rand(3), np.random.random(3) rng.random(3)
np.random.randn(3) rng.standard_normal(3)
np.random.normal(m, s, n) rng.normal(m, s, n)
np.random.randint(lo, hi, n) rng.integers(lo, hi, n) (endpoint=True to include hi)
np.random.choice(a, n) rng.choice(a, n, replace=..., p=...)
np.random.shuffle(a) rng.shuffle(a) (in place), rng.permutation(a) (copy)
np.random.uniform, poisson, binomial, exponential the same names on rng
one seed for several processes rng.spawn(n) or np.random.SeedSequence(42).spawn(n)
names = np.array([" ana ", "Bo", "cy"])
print(np.strings.upper(np.strings.strip(names)), np.strings.str_len(names))
days = np.arange("2024-05-01", "2024-05-04", dtype="datetime64[D]")
print(days, (days[-1] - days[0]).astype(int))
print(np.datetime64("2024-05-01") + np.timedelta64(30, "D"))
print(np.busday_count("2024-05-01", "2024-05-31"))
Output
['ANA' 'BO' 'CY'] [6 2 2]
['2024-05-01' '2024-05-02' '2024-05-03'] 2
2024-05-31
22
np.save("output/a.npy", a) # binary; keeps shape and dtype
a = np.load("output/a.npy")
np.savez_compressed("output/all.npz", x=X, y=price)
with np.load("output/all.npz") as f: # a lazy dict-like archive
X, price = f["x"], f["y"]
np.savetxt("output/a.csv", X, delimiter=",", fmt="%.2f", header="one,sqft")
raw = np.loadtxt("data/readings.txt") # strict: a blank cell raises
gaps = np.genfromtxt("data/sensors.csv", delimiter=",", skip_header=1,
usecols=(2, 3, 4)) # blank cells -> nan

np.strings (new in NumPy 2) holds the vectorized string functions: upper, lower, strip, replace, startswith, find, str_len, slice and more. The older np.char module still works. For real text tables, use pandas or Polars.

NumPy 2: removed names and their replacements

Section titled “NumPy 2: removed names and their replacements”

These names raise AttributeError on NumPy 2. Old tutorials still use them.

Removed Use instead
np.NaN, np.NAN np.nan
np.Inf, np.Infinity, np.infty, np.PINF np.inf
np.NINF -np.inf
np.float_ np.float64
np.complex_, np.cfloat np.complex128
np.string_ np.bytes_
np.unicode_ np.str_
np.bool8 np.bool (or np.bool_)
np.object0, np.int0, np.uint0 np.object_, np.intp, np.uintp
np.product, np.cumproduct np.prod, np.cumprod
np.alltrue, np.sometrue np.all, np.any
np.round_ np.round
np.trapz np.trapezoid
np.in1d np.isin
np.row_stack np.vstack
np.msort(a) np.sort(a, axis=0)
np.asfarray(a) np.asarray(a, dtype=np.float64)
np.find_common_type np.result_type or np.promote_types
np.cast[t](a) a.astype(t)
a.ptp(), a.newbyteorder() np.ptp(a), a.view(a.dtype.newbyteorder())
np.issubclass_, np.set_string_function issubclass, np.set_printoptions
print(np.nan, np.inf, np.float64, np.prod([2, 3]), np.isin([1, 5], [5]))
value = np.NaN
Output
nan inf <class 'numpy.float64'> 6 [False True]
AttributeError: `np.NaN` was removed in the NumPy 2.0 release. Use `np.nan` instead.

Other NumPy 2 changes that affect old code:

  • repr() of a scalar shows its type: np.float64(3.0). print() and f-strings still show 3.0. Lists of NumPy scalars print as [np.int64(1), ...]; use .tolist().
  • The promotion rules above (NEP 50): NumPy scalars are strong, Python numbers are weak, values do not matter.
  • np.array(x, copy=False) raises when a copy is needed. Use np.asarray(x).
  • The default integer is int64 on Windows too.
  • np.linalg.eig returns complex arrays on NumPy 2.5.
Trap Symptom Fix
and, or, not on arrays ValueError: The truth value of an array ... is ambiguous &, |, ~ with parentheses
a > 1 & b < 2 wrong mask or error: & binds tighter than > (a > 1) & (b < 2)
editing a slice the original array changes too a[1:3].copy() before you edit
x == np.nan always False np.isnan(x)
one NaN in the data mean or sum is nan np.nanmean, np.nansum
small integer dtypes np.array([100], np.int8) * 2 is [-56], no warning upcast with astype(np.int64) first
int8_array + 300 OverflowError on NumPy 2 use a wider dtype
float32 data plus np.float64(...) silently becomes float64 on NumPy 2 use a Python float or cast the scalar
astype(int) on floats truncates toward zero, NaN gives garbage np.round first; handle NaN first
np.round(2.5) 2.0 (round half to even) expected; use np.floor(x + 0.5) for half up
(n, m) - (n,) ValueError: operands could not be broadcast keepdims=True or [:, None]
a[[0, 1], [2, 3]] 2 elements, not a 2 × 2 block a[np.ix_([0, 1], [2, 3])]
counts[idx] += 1 with repeats each position counts once np.add.at or np.bincount
np.std(a) vs pandas .std() different numbers NumPy ddof=0, pandas ddof=1; pass ddof
np.empty(n) random-looking values np.zeros or fill every cell
np.arange(0, 1, 0.1) length surprises from float steps np.linspace(0, 1, 11)
reshape on the wrong order values land in the wrong rows check the row order; order="F" for columns
eigenvector and SVD signs signs flip between versions or machines do not interpret a sign alone
np.linalg.eig dtype complex128 even for real results eigh for symmetric matrices
printing scalars in containers [np.float64(1.5)] .tolist(), float(x)
legacy random API non-reproducible code, shared global state rng = np.random.default_rng(42)
removed aliases AttributeError: np.NaN was removed see the table above
object or <U arrays slow, no vectorized math NumPy for numbers; pandas or Polars for text
np.vectorize(f) no speed-up: it is a Python loop write the math with ufuncs, np.where or np.select
growing with np.append in a loop slow: a full copy each time collect in a list, then one np.array

pandas gives Python labeled tables (DataFrame) and labeled columns (Series). This page is a reference for pandas 3.x: input and output, selection, dtypes, groupby, reshaping, joins, time series, text, cleaning, and the pandas 3 rules (copy-on-write, the str dtype, removed APIs). Every block runs in order and shares the setup below.

import numpy as np
import pandas as pd
pd.set_option("display.width", 100) # wrap printed tables at 100 characters
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
df = pd.DataFrame(
{
"store": ["S01", "S02", "S01", "S03", "S02", "S01"],
"region": ["North", "South", "North", "West", "South", "North"],
"month": pd.to_datetime(["2024-01-31", "2024-01-31", "2024-02-29",
"2024-02-29", "2024-03-31", "2024-03-31"]),
"units": [12, 7, 15, 4, 9, 11],
"revenue": [1200.0, 650.0, 1480.0, np.nan, 905.0, 1010.0],
},
index=pd.Index(["a", "b", "c", "d", "e", "f"], name="id"),
)
I want to… Use… Example
read a CSV with dates pd.read_csv(path, parse_dates=[...]) pd.read_csv("data/sales.csv", parse_dates=["order_date"])
read only some columns and rows usecols=, nrows= usecols=["order_date", "revenue"]
read Parquet / Excel / JSON pd.read_parquet, pd.read_excel, pd.read_json pd.read_excel(path, sheet_name="sales")
flatten nested JSON pd.json_normalize(records, record_path=, meta=) one row per nested item
write a file without the index to_csv(path, index=False) df.to_parquet("output/x.parquet")
see size, dtypes and gaps df.shape, df.dtypes, df.info() df.isna().sum()
summary statistics df.describe() describe(include="str") for text
count values s.value_counts(normalize=True, dropna=False) shares with NaN counted
pick columns df[["a", "b"]]
pick rows and columns by label df.loc[rows, cols] df.loc["b":"d", ["units"]] (end included)
pick by position df.iloc[rows, cols] df.iloc[:3, -1] (end excluded)
one cell, fast df.at[label, col], df.iat[i, j] df.at["c", "units"]
filter rows a boolean mask df[(df["units"] > 8) & (df["region"] != "West")]
filter with an expression df.query("...") df.query("units > @k and region == 'North'")
test membership or a range s.isin(list), s.between(lo, hi) s.isin(["North", "East"])
sort by several columns sort_values([a, b], ascending=[True, False]) add a tie-breaker column
top n rows df.nlargest(n, col) sales.nlargest(5, "revenue")
add a column df["new"] = expr or df.assign(new=...) assign(k=lambda d: d["revenue"] / 1000)
if/else and if/elif/else np.where, np.select np.where(s > 0, "up", "down")
set values in some rows df.loc[mask, col] = value never df[col][mask] = value
look up values from a dict s.map(mapping) missing keys → NaN
bin numbers into labels pd.cut(s, bins, labels=...), pd.qcut(s, q) pd.cut(age, [0, 30, 60, 120])
convert text to numbers / dates pd.to_numeric(errors="coerce"), pd.to_datetime(format=...) bad values → NaN / NaT
use an ordered category pd.CategoricalDtype(cats, ordered=True) ["basic", "standard", "premium"]
aggregate per group groupby(key).agg(name=(col, func)) agg(total=("revenue", "sum"))
a group value on every row groupby(key)[col].transform(func) share of group total
keep groups that pass a test groupby(key).filter(func) filter(lambda g: len(g) >= 2)
wide report table pivot_table(index, columns, values, aggfunc) always pass aggfunc
wide → long df.melt(id_vars=..., var_name=..., value_name=...)
join two tables merge(other, on=key, how="left", validate="many_to_one") indicator=True to audit
stack tables with the same columns pd.concat(frames, ignore_index=True)
date parts .dt.year, .dt.month, .dt.day_of_week, .dt.to_period("M")
totals per month resample("ME", on=col) or groupby(pd.Grouper(key=col, freq="ME"))
moving average s.rolling(7).mean() rolling("7D") on a date index
change from the previous row s.diff(), s.pct_change(), s.shift(1) per group: groupby(k)[c].shift()
text methods .str.lower(), .str.contains(), .str.extract()
fill or drop gaps fillna(value), ffill(), interpolate(), dropna(subset=[...]) per group with groupby
find and drop duplicates duplicated(subset, keep=False), drop_duplicates(subset, keep="last")
select from a MultiIndex df.loc[(k1, k2)], df.xs(k2, level="name") sort_index() first
flatten two-level column names ["_".join(c) for c in df.columns.to_flat_index()] after agg({"c": [...]})
compare two frames in a test pd.testing.assert_frame_equal(a, b) checks dtypes too
Format Read Write Keeps dtypes Needs
CSV pd.read_csv(path) df.to_csv(path, index=False) no: dates and categories come back as str —
Parquet pd.read_parquet(path, columns=[...]) df.to_parquet(path, index=False) yes pyarrow
Excel pd.read_excel(path, sheet_name=...) df.to_excel(path, sheet_name=..., index=False) numbers, dates openpyxl
JSON records pd.read_json(path) df.to_json(path, orient="records", date_format="iso") partly —
JSON lines pd.read_json(path, lines=True) df.to_json(path, orient="records", lines=True) partly —
nested JSON pd.json_normalize(data, record_path=, meta=) — partly —
SQL pd.read_sql(query, conn, params=...) df.to_sql(name, conn, index=False) partly a DB driver
clipboard, HTML pd.read_clipboard(), pd.read_html(io.StringIO(html)) df.to_markdown(), df.to_html() no lxml, tabulate
read_csv option Does
usecols=[...] load only these columns
parse_dates=[...] parse these columns as dates (date_format= for one fixed format)
dtype={"col": "category"} set dtypes at load: "category", "int32", "Int64", "str"
index_col="col" use a column as the index
na_values=["-", "?"] extra missing-value tokens
keep_default_na=False stop reading NA, None, null and "" as missing
nrows=1000, skiprows=, chunksize= read part of a file, or in pieces
sep=";", decimal=",", thousands="." European number formats
encoding="latin-1" non-UTF-8 files
dtype_backend="pyarrow" Arrow dtypes for every column
from pathlib import Path
Path("output").mkdir(exist_ok=True) # never write into data/
part = pd.read_parquet("data/sales_sample.parquet", columns=["order_date", "revenue"])
part.to_csv("output/part.csv", index=False)
back = pd.read_csv("output/part.csv")
print(part.dtypes.astype(str).to_dict())
print(back.dtypes.astype(str).to_dict()) # the date is text again
print(part.head(1).to_json(orient="records", date_format="iso"))
Output
{'order_date': 'datetime64[us]', 'revenue': 'float64'}
{'order_date': 'str', 'revenue': 'float64'}
[{"order_date":"2023-01-01T00:00:00.000","revenue":66.49}]
import json
with open("data/customers.json", encoding="utf-8") as f:
export = json.load(f)
flat = pd.json_normalize(export["customers"], sep="_") # nested keys -> columns
orders = pd.json_normalize(export["customers"], record_path="orders",
meta=["customer_id"]) # one row per order
print(flat.shape, [c for c in flat.columns if c.startswith("address_")][:2])
print(orders.columns.to_list(), len(orders))
Output
(20, 12) ['address_street', 'address_city']
['order_id', 'date', 'items', 'amount', 'customer_id'] 48
Call Shows
df.head(n), df.tail(n), df.sample(n, random_state=42) some rows
df.shape, len(df), df.columns, df.index size and labels
df.dtypes, df.info() dtypes; info() prints by itself and returns None
df.describe(), df.describe(include="str") numeric summary; text summary
s.value_counts(), s.nunique(), s.unique() counts, number of distinct values, distinct values
df.isna().sum(), df.isna().mean() gaps per column, share of gaps
df.memory_usage(deep=True) bytes per column, text included
df.corr(numeric_only=True) correlations of numeric columns
print(sales.shape, sales["region"].value_counts().to_dict())
print(sales["channel"].value_counts(normalize=True).round(3).to_dict())
print(df.isna().sum().to_dict(), df["store"].nunique())
print(sales[["unit_price", "quantity"]].describe().loc[["mean", "50%", "max"]])
Output
(20228, 13) {'East': 5396, 'South': 5144, 'North': 4966, 'West': 4722}
{'store': 0.58, 'online': 0.42}
{'store': 0, 'region': 0, 'month': 0, 'units': 0, 'revenue': 1} 3
unit_price quantity
mean 146.333 1.46
50% 69.990 1.00
max 1299.000 25.00
Syntax Selects by Returns Slice end
df["col"] one column name Series —
df[["a", "b"]] column names DataFrame —
df[mask] a boolean Series DataFrame —
df.loc["b":"d", "units":"revenue"] labels DataFrame included
df.loc[mask, ["units"]] mask + labels DataFrame —
df.loc[lambda d: d["units"] > 8] a function of the frame DataFrame —
df.iloc[0:3, [0, -1]] positions DataFrame excluded
df.at["c", "units"], df.iat[2, 3] one cell scalar —
df.query("units > @k and region == 'North'") an expression string DataFrame —
df.filter(like="rev"), df.select_dtypes("number") column names, dtypes DataFrame —
s.iloc[0], s.loc["a"] one value scalar —
print(df.loc["b":"d", ["store", "units"]])
print(df.iloc[-2:, [0, 3]].index.to_list(), df.at["c", "units"], df.iat[2, 3])
k = 8
mask = (df["units"] > k) & df["region"].isin(["North", "South"])
print(df.index[mask].to_list())
print(df.query("units > @k and store != 'S02'").index.to_list()) # @k: a variable
print(df[df["month"].between("2024-02-01", "2024-03-31")].index.to_list())
print(df.select_dtypes("number").columns.to_list())
print(df.filter(like="re").columns.to_list()) # names that contain "re"
Output
store units
id
b S02 7
c S01 15
d S03 4
['e', 'f'] 15 15
['a', 'c', 'e', 'f']
['a', 'c', 'f']
['c', 'd', 'e', 'f']
['units', 'revenue']
['store', 'region', 'revenue']
Need Write
and / or / not (a) & (b), (a) | (b), ~(a); never and, or, not
one of several values s.isin(["x", "y"])
a range s.between(lo, hi); inclusive="left" for lo <= s < hi
missing / present s.isna(), s.notna()
text pattern s.str.contains("pack", case=False)
count / share of matches mask.sum(), mask.mean()
dtype Missing marker Use
int64, float64, bool NaN for float only NumPy dtypes; a gap turns int64 into float64
str NaN default for text in pandas 3 (Arrow-backed, StringDtype(na_value=nan))
string pd.NA the nullable string dtype, opt-in
Int64, Float64, boolean pd.NA nullable numbers and flags (capital letter)
category NaN few distinct, repeated values; ordered if you need <
datetime64[us], timedelta64[us] NaT pandas 3 default unit is microseconds
period[M] NaT calendar periods (months, quarters)
object None, NaN lists, dicts, mixed Python objects
int64[pyarrow] and friends <NA> with dtype_backend="pyarrow"
names = pd.Series(["ana", None, "Bo"])
print(names.dtype, names.dtype == "str", names.isna().tolist())
print(names.str.upper().to_list())
print(pd.Series([3, None]).dtype, pd.Series([3, None], dtype="Int64").to_list())
print(df.convert_dtypes().dtypes.astype(str).to_list()) # whole floats -> Int64
raw = pd.Series(["79.99", "1,299.00", "n/a"])
print(pd.to_numeric(raw.str.replace(",", ""), errors="coerce").to_list())
print(pd.to_datetime(pd.Series(["31/12/2024"]), format="%d/%m/%Y").dt.date.to_list())
Output
str True [False, True, False]
['ANA', nan, 'BO']
float64 [3, <NA>]
['string', 'string', 'datetime64[us]', 'Int64', 'Int64']
[79.99, 1299.0, nan]
[datetime.date(2024, 12, 31)]
plan = pd.Series(["basic", "premium", "standard", "basic"])
levels = pd.CategoricalDtype(["basic", "standard", "premium"], ordered=True)
plan = plan.astype(levels)
print(plan.cat.codes.to_list(), (plan >= "standard").to_list(), plan.max())
print(plan.value_counts(sort=False).to_dict()) # counts in category order
as_str = sales["region"].memory_usage(deep=True)
as_cat = sales["region"].astype("category").memory_usage(deep=True)
print(as_cat < as_str, round(as_str / as_cat, 1)) # category saves memory
Output
[0, 2, 1, 0] [False, True, True, False] premium
{'basic': 2, 'standard': 1, 'premium': 1}
True 12.4
Convert with On a bad value
s.astype("float64"), df.astype({"a": "int32"}) raises ValueError
pd.to_numeric(s, errors="coerce") NaN
pd.to_numeric(s, downcast="integer") the smallest integer dtype that fits
pd.to_datetime(s, format="%Y-%m-%d", errors="coerce") NaT
df.convert_dtypes() nullable dtypes for every column
s.astype("category"), s.cat.codes categories, integer codes
out = df.assign(
price=lambda d: d["revenue"] / d["units"], # vectorized math
size=lambda d: np.where(d["units"] >= 10, "big", "small"), # if/else
band=lambda d: pd.cut(d["units"], [0, 5, 10, 20], labels=["low", "mid", "high"]),
city=lambda d: d["store"].map({"S01": "Chicago", "S02": "Dallas"}), # lookup
)
print(out[["units", "price", "size", "band", "city"]])
df2 = df.copy()
df2["flag"] = False # default first ...
df2.loc[df2["units"] > 10, "flag"] = True # ... then some rows
print(df2["flag"].to_list())
Output
units price size band city
id
a 12 100.000 big high Chicago
b 7 92.857 small mid Dallas
c 15 98.667 big high Chicago
d 4 NaN small low NaN
e 9 100.556 small mid Dallas
f 11 91.818 big high Chicago
[True, False, True, False, False, True]
Task Fast Slow (one Python call per row)
arithmetic on columns df["a"] * df["b"] df.apply(lambda r: r["a"] * r["b"], axis=1)
if/else np.where(cond, x, y), s.where(cond, other) s.apply(lambda v: x if v > 0 else y)
several branches np.select(conds, choices, default) a row function with if/elif
code → label s.map(dict_or_series) s.apply(lambda v: mapping[v])
numbers → bins pd.cut, pd.qcut a loop of if tests
element-wise on every cell df.map(func) — (applymap was removed)
Call Does
s.isna(), s.notna(), pd.isna(x) find gaps (NaN, None, NaT, pd.NA)
df.dropna(subset=["a"]), dropna(thresh=k) drop rows with gaps in a / with fewer than k values
s.fillna(0), s.fillna(s.median()) fill with a constant or a statistic
df.fillna({"a": 0, "b": "unknown"}) one fill value per column
s.fillna(df.groupby(k)[c].transform("median")) fill with the group median
s.ffill(), s.bfill(), groupby(k)[c].ffill() repeat the last / next known value
s.interpolate(), interpolate(method="time") straight line between known values
s.sum(), s.mean() skip NaN by default; skipna=False to propagate it
df[c + "_missing"] = df[c].isna() remember what you filled (do it before the fill)
r = df["revenue"]
print(r.isna().sum(), r.count(), r.mean().round(1), r.mean(skipna=False))
print(r.fillna(r.groupby(df["region"]).transform("median")).to_list())
print(r.ffill().to_list(), r.interpolate().to_list())
print(len(df.dropna(subset=["revenue"])), df.fillna({"revenue": 0})["revenue"].sum())
Output
1 5 1049.0 nan
[1200.0, 650.0, 1480.0, nan, 905.0, 1010.0]
[1200.0, 650.0, 1480.0, 1480.0, 905.0, 1010.0] [1200.0, 650.0, 1480.0, 1192.5, 905.0, 1010.0]
5 5245.0

read_csv reads "", NA, N/A, NULL, null, NaN, nan, None and #N/A as missing by default. It does not read -, ?, unknown, 0 or 999 as missing: pass na_values=.

log = pd.DataFrame({"order": ["O1", "O1", "O2", "O3", "O3"],
"version": [1, 1, 1, 1, 2], "qty": [2, 2, 5, 1, 3]})
print(log.duplicated().sum(), log.duplicated(subset="order", keep=False).to_list())
latest = log.sort_values(["order", "version"]).drop_duplicates("order", keep="last")
print(latest.to_dict("list"))
print(log.loc[log.groupby("order")["version"].idxmax(), "qty"].to_list())
Output
1 [True, True, False, True, True]
{'order': ['O1', 'O2', 'O3'], 'version': [1, 1, 2], 'qty': [2, 5, 3]}
[2, 5, 3]
Call Marks or keeps
df.duplicated() rows equal to an earlier row in every column
df.duplicated(subset=key) rows whose key appeared before
keep="first" / "last" / False leave the first / last copy unmarked / mark every copy
df.drop_duplicates(subset=key, keep="last") one row per key, the last in table order
df.loc[df.groupby(key)[t].idxmax()] one row per key, the latest by t
by_region = df.groupby("region")
print(by_region.agg(total=("revenue", "sum"), orders=("store", "size"),
stores=("store", "nunique"), best=("units", "max")))
share = df["units"] / by_region["units"].transform("sum") # one value per row
print(share.round(2).to_list())
print(by_region.filter(lambda g: len(g) >= 2).index.to_list())
print(df.groupby("store", as_index=False)["units"].sum().to_dict("list"))
print(by_region["units"].rank(ascending=False).to_list(), by_region.size().to_dict())
Output
total orders stores best
region
North 3690.0 3 1 15
South 1555.0 2 1 9
West 0.0 1 1 4
[0.32, 0.44, 0.39, 1.0, 0.56, 0.29]
['a', 'b', 'c', 'e', 'f']
{'store': ['S01', 'S02', 'S03'], 'units': [38, 16, 4]}
[2.0, 2.0, 1.0, 1.0, 1.0, 3.0] {'North': 3, 'South': 2, 'West': 1}
Method Returns Use for
g.agg(...), g.sum(), g.mean() one row per group report tables
g.size() / g.count() rows per group / non-missing values per column sizes, completeness
g.sum(min_count=1) NaN for a group with no values the default gives 0.0 (West above)
g.transform(func) one value per input row shares, z-scores, group fills
g.filter(func) the rows of groups where func(group) is True drop small groups
g.rank(), g.cumsum(), g.cumcount() one value per row order within a group
g.shift(n), g.diff(), g.pct_change() one value per row change within each group
g.head(n), g.nth(k), g.idxmax() some input rows or labels top rows per group
g.apply(func) anything last resort: slow; the group keys are not passed to func
Aggregation form Result columns
g["revenue"].agg(["sum", "mean"]) sum, mean
g.agg({"revenue": "sum", "units": "max"}) the source names
g.agg(total=("revenue", "sum")) total (named aggregation, preferred)
g.agg(p90=("revenue", lambda s: s.quantile(0.9))) p90 (a lambda runs in Python per group)
groupby parameter pandas 3 default Effect
as_index True False keeps the keys as columns
sort True False keeps first-appearance order (faster)
observed True False adds empty categories
dropna True False keeps a NaN key as its own group
Tool Direction Aggregates Key arguments
df.pivot_table long → wide yes (default "mean") index, columns, values, aggfunc, margins, fill_value
df.pivot long → wide no; duplicate pairs raise ValueError index, columns, values
pd.crosstab(a, b) two columns → counts counts or values= + aggfunc= normalize="index", margins=True
df.melt wide → long — id_vars, value_vars, var_name, value_name
s.unstack(level) index level → columns — fill_value
df.stack() columns → index level — keeps NaN cells in pandas 3
df.explode(col) list cells → rows — ignore_index=True
wide = df.assign(month=df["month"].dt.month).pivot_table(
index="region", columns="month", values="units",
aggfunc="sum", fill_value=0, margins=True, margins_name="Total")
print(wide)
long = wide.drop(index="Total", columns="Total").reset_index().melt(
id_vars="region", var_name="month", value_name="units")
print(long.shape, long.query("units > 0")["units"].sum())
print(pd.crosstab(df["region"], df["store"]))
print(df.set_index(["region", "store"])["units"].groupby(level=0).sum().to_dict())
Output
month 1 2 3 Total
region
North 12 15 11 38
South 7 0 9 16
West 0 4 0 4
Total 19 19 20 58
(9, 3) 58
store S01 S02 S03
region
North 3 0 0
South 0 2 0
West 0 0 1
{'North': 38, 'South': 16, 'West': 4}

A MultiIndex has several key levels. It comes out of groupby([k1, k2]), pivot_table, set_index([...]) and agg({"c": ["sum", "max"]}) (on the columns).

Task Code
make one from columns df.set_index(["region", "store"])
make every combination pd.MultiIndex.from_product([regions, years], names=["region", "year"])
sort it (needed before slices) mi = mi.sort_index()
select by the outer level / a full key mi.loc["North"], mi.loc[("North", "S01")]
select by an inner level mi.xs("S01", level="store")
slice several levels mi.loc[pd.IndexSlice[:, ["S01", "S03"]], :]
aggregate one level mi.groupby(level="region").sum()
drop or swap levels mi.droplevel("region"), mi.swaplevel()
levels back to columns mi.reset_index()
flatten two-level column names df.columns = ["_".join(c) for c in df.columns.to_flat_index()]
mi = df.groupby(["region", "store"])[["units", "revenue"]].sum().sort_index()
print(mi.index.names, mi.loc[("North", "S01"), "units"])
print(mi.xs("S02", level="store")["units"].to_dict())
print(mi.loc[pd.IndexSlice[:, ["S01", "S03"]], "units"].to_list())
two = df.groupby("region").agg({"units": ["sum", "max"]}) # two-level columns
print(two.columns.to_list())
two.columns = ["_".join(c) for c in two.columns.to_flat_index()]
print(two)
Output
['region', 'store'] 38
{'South': 16}
[38, 4]
[('units', 'sum'), ('units', 'max')]
units_sum units_max
region
North 38 15
South 16 9
West 4 4
flowchart LR
    L["long: one row per observation"] -- "pivot<br/>pivot_table<br/>unstack" --> W["wide: one column per key value"]
    W -- "melt<br/>stack" --> L
merge argument Values Note
how "inner" (default), "left", "right", "outer", "cross" cross: every pair of rows
on / left_on, right_on key columns same name / different names
left_index, right_index True use the index as the key
validate "one_to_one", "one_to_many", "many_to_one", "many_to_many" raises MergeError when the data breaks it
indicator True adds _merge: left_only, right_only, both
suffixes ("_x", "_y") for clashing non-key columns
Tool Joins on Default how
left.merge(right, on=key) columns "inner"
left.join(right) the index of right "left"
pd.concat(frames) stacks rows (axis=0) or columns (axis=1, aligned on the index) outer union of columns
pd.merge_asof(left, right, on=t, by=k) the nearest earlier key (both sorted) direction="backward"
stores = pd.DataFrame({"store": ["S01", "S02", "S04"],
"city": ["Chicago", "Dallas", "Miami"]})
m = df.merge(stores, on="store", how="left", validate="many_to_one", indicator=True)
print(m["_merge"].value_counts().to_dict(), len(df), len(m))
audit = df[["store"]].drop_duplicates().merge(stores, how="outer", indicator=True)
print(audit[["store", "_merge"]].to_dict("list"))
print(pd.concat([df.head(2), df.tail(1)], ignore_index=True).index.to_list())
print(pd.concat([df["units"], df["revenue"]], axis=1, keys=["u", "r"]).shape)
Output
{'both': 5, 'left_only': 1, 'right_only': 0} 6 6
{'store': ['S01', 'S02', 'S03', 'S04'], '_merge': ['both', 'both', 'left_only', 'right_only']}
[0, 1, 2]
(6, 2)
dupes = pd.DataFrame({"store": ["S01", "S01"], "city": ["Chicago", "Evanston"]})
bad = df.merge(dupes, on="store", how="left", validate="many_to_one")
Output
pandas.errors.MergeError: Merge keys are not unique in right dataset; not a many-to-one merge
Relationship Example Rows after a left merge
many-to-one order lines → stores the same as the left table
one-to-one customers → their profile the same as the left table
one-to-many stores → order lines grows: one row per match
many-to-many lines → lines of the same order grows fast; validate on purpose
.dt accessor Gives
year, quarter, month, day, hour numbers
day_of_week (Monday = 0), day_name(), month_name() weekday and month
is_month_end, days_in_month, day_of_year calendar facts
isocalendar().week ISO week number
to_period("M"), to_period("Q") period labels for grouping
strftime("%Y-%m") text labels
floor("D"), normalize(), tz_localize("UTC"), tz_convert(...) drop the time, time zones
Frequency alias Means
"D", "B", "W" ("W-MON") day, business day, week ending Sunday (or Monday)
"ME", "MS" month end, month start
"QE", "QS", "YE", "YS" quarter and year, end or start
"h", "min", "s", "ms" hour, minute, second, millisecond
monthly = sales.resample("ME", on="order_date")["revenue"].sum() # calendar months
print(monthly.tail(3).round(0))
q = sales.groupby([sales["order_date"].dt.to_period("Q"), "channel"])["revenue"].sum()
print(q.unstack().tail(2).round(0))
daily = sales.groupby("order_date")["revenue"].sum()
trend = pd.DataFrame({"rev": daily, "ma7": daily.rolling(7).mean(),
"d7": daily.rolling("7D").sum(), "chg": daily.pct_change()})
print(trend.tail(2).round(2))
d = sales["order_date"].head(1)
print(d.dt.day_name().item(), d.dt.day_of_week.item(), d.dt.isocalendar().week.item())
Output
order_date
2024-10-31 166148.0
2024-11-30 268467.0
2024-12-31 302912.0
Freq: ME, Name: revenue, dtype: float64
channel online store
order_date
2024Q3 200792.0 241643.0
2024Q4 384905.0 352621.0
rev ma7 d7 chg
order_date
2024-12-30 14734.24 8382.76 58679.29 0.58
2024-12-31 7961.18 8609.74 60268.21 -0.46
Sunday 6 52
Window Call Note
last n rows s.rolling(n).mean() NaN until n values; min_periods= lowers that
last 7 days s.rolling("7D").sum() needs a sorted DatetimeIndex; robust to missing days
centered s.rolling(7, center=True) uses future values: not for forecasts
from the start s.expanding().max(), s.cummax() running totals and records
weighted to recent rows s.ewm(span=7).mean() α=2/(span+1)\alpha = 2 / (\text{span} + 1)
previous value s.shift(1), s.diff(), s.pct_change() shift(-1) reads the future
per group df.groupby(k)[c].transform(lambda s: s.rolling(3).mean()) sort by time first
Method Does
lower(), upper(), title(), strip() case and whitespace
contains(pat, case=False, regex=True), startswith, endswith boolean masks
fullmatch(r"C\d{5}") the whole value matches a pattern
replace(pat, repl, regex=False) substitute text (pass regex=True for patterns)
split(sep, n=1, expand=True) split into columns
extract(r"(?P<num>\d+)-(?P<unit>\w+)") one column per group, named by the group
len(), str[:3], zfill(5), pad(8) length, slicing, padding
normalize("NFC") unify Unicode forms of accents
cat(sep=", ") join all values into one string
names = pd.Series([" Running Socks 3-Pack", "55-inch 4K TV ", None])
clean = names.str.strip().str.lower()
print(clean.to_list(), clean.str.contains("pack").to_list())
print(names.str.extract(r"(?P<num>\d+)-(?P<unit>inch|Pack)").to_dict("list"))
print(names.str.split(" ", n=1, expand=True).shape, clean.str.len().to_list())
Output
['running socks 3-pack', '55-inch 4k tv', nan] [True, False, False]
{'num': ['3', '55', nan], 'unit': ['Pack', 'inch', nan]}
(3, 2) [20.0, 13.0, nan]

A chain reads top to bottom, creates no temporary names, and never mutates its input.

def add_weekday(frame: pd.DataFrame) -> pd.DataFrame:
return frame.assign(weekday=frame["order_date"].dt.day_name())
top_days = (
sales
.query("category == 'Books' and order_date.dt.year == 2024") # filter
.pipe(add_weekday) # your own step
.groupby("weekday")
.agg(revenue=("revenue", "sum"), orders=("order_id", "nunique"))
.assign(share=lambda d: d["revenue"] / d["revenue"].sum()) # sees the chain
.sort_values(["share", "orders"], ascending=False)
.head(2)
)
print(top_days)
Output
revenue orders share
weekday
Saturday 11544.66 258 0.201
Sunday 9509.37 231 0.166
Step In a chain
assign(new=lambda d: ...) add or replace columns; the lambda sees the current frame
query("..."), loc[lambda d: ...] filter rows
pipe(func, *args) call func(df, *args)
rename(columns=...), astype({...}) rename, change dtypes
sort_values, head, nlargest, reset_index order and trim

pandas 3 always uses copy-on-write (CoW). Every selection or method result behaves as a copy. pandas copies the data only when one side is written to, so selections stay cheap.

Code pandas 3 behavior Do this
sub = df[df["a"] > 1]; sub["b"] = 0 changes sub only, no warning fine; df is safe
df["b"][mask] = 0 changes nothing; ChainedAssignmentError warning df.loc[mask, "b"] = 0
df.loc[mask]["b"] = 0 changes nothing; warning df.loc[mask, "b"] = 0
s = df["b"]; s.iloc[0] = 9 changes s only write through df.loc / df.iloc
arr = df["b"].to_numpy() a read-only view .to_numpy().copy() to edit
df.copy() still useful for a clear, independent working table
SettingWithCopyWarning gone CoW replaced it
sub = df[df["units"] > 10]
sub["units"] = 0 # writes only to sub
print(df["units"].to_list(), sub["units"].to_list())
col = df["units"]
col.iloc[0] = -1 # col is a copy now
print(df.at["a", "units"], col.iloc[0])
fixed = df.copy()
fixed.loc[fixed["units"] > 10, "units"] = 10 # the right way to write
print(fixed["units"].to_list())
Output
[12, 7, 15, 4, 9, 11] [0, 0, 0]
12 -1
[10, 7, 10, 4, 9, 10]
df["units"][df["units"] > 10] = 0 # ChainedAssignmentError warning; df is unchanged
Old code pandas 3 Use instead
text columns are object text is str select_dtypes(include="str"), dtype == "str"
select_dtypes(include="object") for text Pandas4Warning include="str"
df[col][mask] = v does nothing, warns df.loc[mask, col] = v
df.loc[0, "int_col"] = 1.5 TypeError (no silent upcast) df["int_col"] = df["int_col"].astype("float64") first
s[0] on a text index KeyError (no positional fallback) s.iloc[0]
inplace=True on sort_values, dropna, drop, rename, set_index, reset_index, drop_duplicates, query Pandas4Warning df = df.sort_values(...)
df.applymap(f) removed df.map(f)
fillna(method="ffill") TypeError ffill(), bfill()
df.pad(), df.first("2D"), df.swapaxes, s.ravel() removed ffill(), df.loc[:start + offset], df.T, s.to_numpy().ravel()
df.append(other) removed pd.concat([df, other])
freq="M", "Q", "Y", "H", "T", "S" ValueError "ME", "QE", "YE", "h", "min", "s"
.dt.weekday, .dt.dayofweek Pandas4Warning .dt.day_of_week
.dt.week, .dt.weekofyear removed .dt.isocalendar().week
groupby(..., axis=1) TypeError df.T.groupby(...)
groupby().apply(f, include_groups=True) ValueError select the columns f needs
read_csv(delim_whitespace=True) TypeError sep=r"\s+"
to_datetime(infer_datetime_format=True) TypeError format=... or format="ISO8601"
to_json() with datetimes Pandas4Warning date_format="iso"
stack() dropped NaN cells keeps them .dropna() after stack()
pd.options.mode.copy_on_write deprecated; CoW is always on remove the option
.values still works; a pandas array for text .to_numpy()
datetime64[ns] everywhere datetime64[us] from parsing do not hard-code ns
ints = pd.DataFrame({"n": [1, 2]})
ints.loc[0, "n"] = 1.5 # pandas 3 refuses to upcast int64 silently
Output
TypeError: Invalid value '1.5' for dtype 'int64'
Trap Symptom Fix
and, or, not on a Series ValueError: The truth value of a Series is ambiguous &, |, ~
df["a"] > 1 & df["b"] < 2 ValueError (ambiguous truth value) or TypeError: & binds first parentheses around each test
chained assignment the table does not change df.loc[mask, col] = value
loc vs iloc slices one row more or fewer than expected loc includes the end label; iloc excludes it
iloc[0] after a filter or sort not the row labeled 0 use loc for labels
print(df.info()) an extra None line call df.info() alone
to_csv without index=False Unnamed: 0 column on the next read index=False
CSV round trip dates and categories come back as str Parquet, or parse_dates and dtype on read
an int column with one blank loads as float64 dtype={"col": "Int64"}
pivot_table without aggfunc averages, not totals always pass aggfunc
pivot with duplicate pairs ValueError: Index contains duplicate entries pivot_table with aggfunc
agg result assigned as a column all NaN (labels do not match) transform
merge on a duplicated key silently more rows validate= and compare len()
clashing columns after a merge _x and _y names select columns first or set suffixes
sum of an all-NaN group 0.0, which looks like a real total sum(min_count=1) gives NaN
groupby on a key with gaps the NaN rows vanish dropna=False or fill the key
errors="coerce" bad values become NaN silently count isna() before and after
format="mixed", dayfirst=True ISO dates read as year-day-month parse each known format explicitly
s.map(dict) NaN for missing keys s.map(d).fillna(s) or check the keys
>= on an unordered category TypeError CategoricalDtype(..., ordered=True)
rolling(7) vs rolling("7D") different numbers when days are missing pick rows or days on purpose
a sort with ties, then head() unstable top rows add a tie-breaker column
str.replace("$", "") with regex=True removes nothing ($ is an anchor) regex=False or [$]
astype("int8") on big values wraps around silently pd.to_numeric(downcast="integer")
apply(axis=1) on big tables very slow vectorized column math, np.where, map
df.equals(other) False on a dtype difference you cannot see pd.testing.assert_frame_equal for a clear message

Polars is a fast DataFrame library with no index, strict dtypes and a lazy query optimizer. This page covers the expression API, grouping, joins, windows, the lazy API and file IO, with examples on the course tables data/sales.csv, data/stores.csv and data/products.csv. Every runnable block uses Polars 2.1.

I want to… Use… Example
fix the table display pl.Config.set_* pl.Config.set_tbl_width_chars(100)
read a CSV with dates pl.read_csv(..., try_parse_dates=True) pl.read_csv("data/sales.csv", try_parse_dates=True)
read a big file lazily pl.scan_csv, pl.scan_parquet pl.scan_parquet("lake/*.parquet")
see column names and dtypes df.schema, lf.collect_schema() df.schema["order_date"]
pick columns df.select(...) df.select("order_id", "revenue")
pick columns by dtype or name pattern selectors df.select(cs.numeric()), cs.starts_with("unit")
add or replace a column df.with_columns(...) df.with_columns(net=pl.col("revenue") * 0.9)
keep rows df.filter(...) df.filter(pl.col("discount") > 0, pl.col("region") == "East")
a constant value pl.lit(v) pl.lit("bulk")
if / elif / else pl.when().then().otherwise() pl.when(c).then(pl.lit("a")).otherwise(pl.lit("b"))
map values with a dict .replace(d), .replace_strict(d) pl.col("region").replace({"East": "E"})
change a dtype .cast(dtype) pl.col("quantity").cast(pl.Float64)
fill or drop nulls .fill_null(v), df.drop_nulls() pl.col("discount").fill_null(0)
sort with a tie-breaker df.sort(a, b, descending=[...]) df.sort("revenue", "order_id", descending=[True, False])
largest N rows df.top_k(n, by=) df.top_k(3, by="revenue")
one row per key df.unique(subset=, keep=) df.unique("customer_id", keep="first", maintain_order=True)
aggregate per group df.group_by(k).agg(...) df.group_by("region").agg(pl.col("revenue").sum())
keep the order of first appearance maintain_order=True df.group_by("region", maintain_order=True)
count rows per group pl.len() .agg(lines=pl.len())
count values s.value_counts(sort=True) sales["channel"].value_counts(sort=True)
group value on every row .over(keys) pl.col("revenue").sum().over("region")
rank inside groups .rank(...).over(...) pl.col("revenue").rank("ordinal", descending=True).over("region")
running total in time order .cum_sum().over(k, order_by=) pl.col("revenue").cum_sum().over("store_id", order_by="order_date")
time buckets .dt.truncate("1mo"), group_by_dynamic group_by(month=pl.col("order_date").dt.truncate("1mo"))
join tables df.join(o, on=, how=) sales.join(stores, on="store_id", how="left")
rows with / without a match how="semi" / how="anti" stores.join(sales, on="store_id", how="anti")
prove the join keys are unique validate="m:1" sales.join(products, on="product_id", validate="m:1")
nearest earlier match df.join_asof(o, on=, by=) prices.join_asof(rates, on="date")
long → wide / wide → long df.pivot(...) / df.unpivot(...) df.pivot(on="channel", index="region", values="units")
stack tables pl.concat([a, b]) pl.concat([a, b], how="diagonal")
flatten nested JSON .explode() and .unnest() df.explode("customers").unnest("customers")
see the optimized plan lf.explain() print(lf.explain())
run a lazy query lf.collect() lf.collect()
write without loading all rows lf.sink_parquet(path) lf.sink_parquet("sales_2024.parquet")
one value out of a frame .item() df.select(pl.col("revenue").sum()).item()
compare two frames in a test assert_frame_equal from polars.testing import assert_frame_equal
convert to / from pandas df.to_pandas(), pl.from_pandas(pdf) pl.from_pandas(pdf)
hand features to scikit-learn df.to_numpy() X = df.select("quantity", "discount").to_numpy()
run SQL on a frame df.sql(...) sales.sql("SELECT region, count(*) FROM self GROUP BY 1")

Polars draws tables with box borders. Its defaults depend on the terminal, so fix them once at the top of a script or notebook.

import polars as pl
import polars.selectors as cs
pl.Config.set_tbl_rows(8) # at most 8 rows (first 4, …, last 4)
pl.Config.set_tbl_cols(8) # at most 8 columns
pl.Config.set_tbl_width_chars(100) # never wider than 100 characters
pl.Config.set_fmt_str_lengths(30) # show up to 30 characters of text
pl.Config.set_fmt_float("full") # no scientific notation for big floats
sales = pl.read_csv("data/sales.csv", try_parse_dates=True)
stores = pl.read_csv("data/stores.csv", try_parse_dates=True)
products = pl.read_csv("data/products.csv", try_parse_dates=True)
print(sales.shape, stores.shape, products.shape)
print(sales.schema["order_date"], sales.schema["quantity"], sales.schema["revenue"])
Output
(20228, 13) (12, 5) (30, 6)
Date Int64 Float64
Setting Effect
set_tbl_rows(n) rows shown; -1 shows all
set_tbl_cols(n) columns shown; hidden columns become one … column
set_tbl_width_chars(n) maximum table width; long cells wrap
set_fmt_str_lengths(n) characters shown per text cell
set_fmt_float("full") every digit, never 3.5965e6
set_tbl_hide_dataframe_shape(True) drop the shape: (r, c) line
with pl.Config(tbl_rows=20): change settings for one block only
Object What it is Made by
pl.Series one named, typed column pl.Series("x", [1, 2]), df["x"], df.get_column("x")
pl.DataFrame columns of equal length; no index pl.DataFrame(dict), pl.read_csv, pl.from_pandas
pl.LazyFrame a query plan; no data until collect() pl.scan_csv, df.lazy()
pl.Expr a recipe for a column, run inside a context pl.col("x") * 2, pl.len(), pl.lit(0)
Dtype Prints as Notes
pl.String str UTF-8 text (pl.Utf8 is an alias)
pl.Int64, pl.Int32, pl.Int8 i64, i32, i8 .dt.year() is i32, .dt.month() is i8
pl.UInt32 u32 pl.len(), n_unique(), rank("min") (the default rank() is f64)
pl.Float64 f64 NaN is a float value; null means missing
pl.Boolean bool the mean is the share of true
pl.Date, pl.Datetime("us"), pl.Duration date, datetime[μs], duration[μs] b - a gives a Duration
pl.Enum([...]), pl.Categorical enum, cat fixed list of values / values learned from data
pl.List(inner), pl.Struct(fields) list[...], struct[n] .list and .struct namespaces

An expression describes a column. It does nothing until a context runs it, so you can store it in a variable and reuse it. Polars runs the expressions of one context in parallel.

Context Returns Example
df.select(e, name=e) only the listed columns df.select("region", net=pl.col("revenue") * 0.9)
df.with_columns(e, name=e) all columns plus new or replaced ones df.with_columns(pl.col("product").str.to_uppercase())
df.filter(p1, p2) rows where every predicate is true df.filter(pl.col("quantity") > 2)
df.group_by(k).agg(e) one row per group df.group_by("region").agg(pl.col("revenue").mean())
df.sort(e) the same rows, reordered df.sort(pl.col("product").str.len_chars())
Code Selects
"a", pl.col("a") one column (a string works in select, group_by, sort)
pl.col("a", "b") several columns; the expression runs on each
pl.col(pl.Float64), pl.col(pl.Int64, pl.Float64) every column of these dtypes
pl.col("^unit_.*$") a regular expression (must start with ^ and end with $)
pl.all(), pl.all().exclude("id") every column, or every column but some
pl.first(), pl.last(), pl.nth(2) by position
cs.numeric(), cs.string(), cs.temporal(), cs.by_dtype(pl.Date) selectors by dtype
cs.starts_with("unit"), cs.ends_with("_id"), cs.contains("date") selectors by name
cs.string() - cs.by_name("order_id") combine selectors with |, &, -, ~
.name.suffix("_z"), .name.prefix("log_") rename the outputs of a multi-column expression
Expression Meaning
+ - * / // % ** arithmetic, element by element
== != < <= > >= comparison → Boolean
(a > 0) & (b > 0), |, ~ and, or, not (parentheses required)
.is_in([...]), .is_between(lo, hi) membership, inclusive range
.is_null(), .is_not_null(), .fill_null(v), .fill_null(strategy="forward") missing values
.is_nan(), .fill_nan(v) float NaN (not the same as null)
.cast(pl.Int32), .cast(pl.Int32, strict=False) change dtype; strict=False turns failures into null
.alias("name") name the result (same as name=expr in a context)
.round(2), .abs(), .clip(0, 100), .log(), .sqrt() numeric helpers
.sum(), .mean(), .median(), .std(), .quantile(0.9), .n_unique() reduce to one value
.shift(1), .diff(), .pct_change() compare with an earlier row (sort first)
.cum_sum(), .cum_max(), .cum_count() running values
.rolling_mean(7), .rolling_sum(7, min_samples=1) trailing windows over rows
.rank("dense", descending=True) rank; methods average, min, max, dense, ordinal
.filter(cond) keep some values (inside agg or select)
.sort_by("y"), .first(), .last() order values, then pick
pl.when(c1).then(a).when(c2).then(b).otherwise(d) conditional value; first true branch wins
pl.format("{}-{}", a, b), pl.concat_str([a, b], separator="-") build text
pl.date(2024, 1, 1), pl.duration(days=7) date and duration literals
.str method Does
to_uppercase(), to_lowercase(), to_titlecase() change case
strip_chars(), strip_chars_start("0") remove spaces or given characters
len_chars(), slice(0, 3), head(3) length, substring
contains(p), contains(s, literal=True), starts_with(s), ends_with(s) tests (contains uses regex by default)
replace(p, r), replace_all(p, r) replace the first / every match
extract(r"(\d+)", 1), extract_all(r"\d+") regex groups
split(" "), join("-") text → list column; column → one string
to_date("%d/%m/%Y"), to_datetime(fmt), to_integer() parse text
.dt method Does
year(), quarter(), month(), day(), hour() date parts
weekday() Monday = 1 … Sunday = 7 (pandas: Monday = 0)
truncate("1mo"), truncate("1w") round down to the period start
strftime("%Y-%m") format as text
offset_by("1mo"), month_end() calendar arithmetic
total_days(), total_hours() on a Duration

Period strings: "1d", "1w", "1mo", "1q", "1y", "1h", "15m", "30s".

gross = pl.col("unit_price") * pl.col("quantity") # a recipe, reusable
report = (
sales.with_columns(gross=gross) # all columns + gross
.with_columns(saved=(pl.col("gross") - pl.col("revenue")).round(2)) # uses gross
.filter(pl.col("channel") == "online", pl.col("discount") >= 0.15) # comma = AND
.select(
"order_id",
"category",
"saved",
size=pl.when(pl.col("quantity") >= 3)
.then(pl.lit("bulk"))
.otherwise(pl.lit("single")),
)
.sort("saved", "order_id", descending=[True, False]) # order_id breaks ties
.head(4)
)
print(report)
Output
shape: (4, 4)
┌──────────┬─────────────┬───────┬────────┐
│ order_id ┆ category ┆ saved ┆ size │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 ┆ str │
╞══════════╪═════════════╪═══════╪════════╡
│ O014571 ┆ Electronics ┆ 779.4 ┆ bulk │
│ O013545 ┆ Electronics ┆ 519.6 ┆ single │
│ O005024 ┆ Electronics ┆ 459.6 ┆ single │
│ O008251 ┆ Electronics ┆ 459.6 ┆ single │
└──────────┴─────────────┴───────┴────────┘
print(sales.select(cs.numeric().max()).row(0)) # one expression, 4 columns
print(sales.select(cs.string() - cs.ends_with("_id")).columns)
print(sales.select(pl.col("revenue").sum().round(2), lines=pl.len()).rows())
Output
(1299.0, 25, 0.2, 5196.0)
['region', 'channel', 'product', 'category']
[(3596523.83, 20228)]

Group order is not stable between runs. maintain_order=True keeps the order in which each key first appears; .sort(...) gives a fixed order of your choice.

by_region = sales.group_by("region", maintain_order=True).agg(
revenue=pl.col("revenue").sum().round(2),
lines=pl.len(),
orders=pl.col("order_id").n_unique(),
online_share=(pl.col("channel") == "online").mean().round(3),
big=pl.col("revenue").filter(pl.col("revenue") > 1000).len(),
top_product=pl.col("product").sort_by("revenue").last(),
)
print(by_region)
Output
shape: (4, 7)
┌────────┬───────────┬───────┬────────┬──────────────┬─────┬──────────────────────────┐
│ region ┆ revenue ┆ lines ┆ orders ┆ online_share ┆ big ┆ top_product │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ u32 ┆ u32 ┆ f64 ┆ u32 ┆ str │
╞════════╪═══════════╪═══════╪════════╪══════════════╪═════╪══════════════════════════╡
│ West ┆ 822844.57 ┆ 4722 ┆ 3497 ┆ 0.413 ┆ 220 ┆ 14-inch Ultrabook Laptop │
│ South ┆ 891766.07 ┆ 5144 ┆ 3766 ┆ 0.413 ┆ 234 ┆ 14-inch Ultrabook Laptop │
│ East ┆ 993683.72 ┆ 5396 ┆ 4002 ┆ 0.422 ┆ 284 ┆ 14-inch Ultrabook Laptop │
│ North ┆ 888229.47 ┆ 4966 ┆ 3612 ┆ 0.432 ┆ 231 ┆ 55-inch 4K Smart TV │
└────────┴───────────┴───────┴────────┴──────────────┴─────┴──────────────────────────┘
monthly = (
sales.group_by(month=pl.col("order_date").dt.truncate("1q")) # a key expression
.agg(pl.col("revenue").sum().round(0))
.sort("month")
)
print(monthly.head(3))
print(sales.group_by("channel").len().sort("channel").rows()) # rows per group
Output
shape: (3, 2)
┌────────────┬─────────┐
│ month ┆ revenue │
│ --- ┆ --- │
│ date ┆ f64 │
╞════════════╪═════════╡
│ 2023-01-01 ┆ 291278 │
│ 2023-04-01 ┆ 383639 │
│ 2023-07-01 ┆ 412017 │
└────────────┴─────────┘
[('online', 8495), ('store', 11733)]
Aggregation Meaning
pl.len() rows in the group
pl.col("x").count() non-null values
sum(), mean(), median(), min(), max(), std(), quantile(q) statistics; nulls are skipped
n_unique() distinct values
first(), last() first / last value in row order
pl.col("x").filter(cond).sum() aggregate only the rows that pass cond
pl.col("x").sort_by("y").last() the x of the row with the largest y
pl.col("x") alone, or implode() every value of the group as a List
pl.col("a", "b").sum() one aggregation on several columns
Grouping helper Use
group_by("a", "b") several keys
group_by(year=pl.col("d").dt.year()) a computed key with a name
group_by(...).len(); .first(), .mean() rows per group; one aggregation of every column
group_by_dynamic("d", every="1mo") calendar windows on a sorted date column
rolling(index_column="d", period="7d") a trailing time window per row
partition_by("region", as_dict=True) split into one frame per key

expr.over(keys) computes expr per group and puts the result back on every row of that group, like groupby().transform() in pandas or OVER (PARTITION BY ...) in SQL. The row count does not change.

daily = sales.group_by("store_id", "order_date").agg(pl.col("revenue").sum().round(2))
windows = daily.with_columns(
share=(pl.col("revenue") / pl.col("revenue").sum().over("store_id")).round(4),
rank=pl.col("revenue").rank("min", descending=True).over("store_id"),
cum=pl.col("revenue").cum_sum().over("store_id", order_by="order_date").round(2),
prev=pl.col("revenue").shift(1).over("store_id", order_by="order_date"),
)
print(windows.filter(pl.col("store_id") == "S01").sort("order_date").head(4))
Output
shape: (4, 7)
┌──────────┬────────────┬─────────┬────────┬──────┬─────────┬─────────┐
│ store_id ┆ order_date ┆ revenue ┆ share ┆ rank ┆ cum ┆ prev │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ date ┆ f64 ┆ f64 ┆ u32 ┆ f64 ┆ f64 │
╞══════════╪════════════╪═════════╪════════╪══════╪═════════╪═════════╡
│ S01 ┆ 2023-01-01 ┆ 1227.43 ┆ 0.003 ┆ 95 ┆ 1227.43 ┆ null │
│ S01 ┆ 2023-01-03 ┆ 153.99 ┆ 0.0004 ┆ 468 ┆ 1381.42 ┆ 1227.43 │
│ S01 ┆ 2023-01-04 ┆ 143.5 ┆ 0.0004 ┆ 477 ┆ 1524.92 ┆ 153.99 │
│ S01 ┆ 2023-01-06 ┆ 549.44 ┆ 0.0014 ┆ 232 ┆ 2074.36 ┆ 143.5 │
└──────────┴────────────┴─────────┴────────┴──────┴─────────┴─────────┘
Pattern Code
group total on every row pl.col("x").sum().over("k")
share of the group pl.col("x") / pl.col("x").sum().over("k")
rank inside the group pl.col("x").rank("ordinal", descending=True).over("k")
top N per group df.filter(pl.col("x").rank("ordinal", descending=True).over("k") <= 3)
running total in time order pl.col("x").cum_sum().over("k", order_by="date")
previous value in the group pl.col("x").shift(1).over("k", order_by="date")
first row per group df.filter(pl.col("date") == pl.col("date").min().over("k"))
several keys .over("region", "channel")
one list per group .over("k", mapping_strategy="join")
grand total (no keys) pl.col("x").sum() in with_columns broadcasts
targets = pl.DataFrame({"store_id": ["S01", "S07", "S13"], "target": [4, 5, 1]})
for how in ["inner", "left", "full", "semi", "anti"]:
j = targets.join(stores, on="store_id", how=how, coalesce=True)
print(f"{how:<5} rows={j.height:>2} cols={j.width}", sorted(j["store_id"])[-3:])
Output
inner rows= 2 cols=6 ['S01', 'S07']
left rows= 3 cols=6 ['S01', 'S07', 'S13']
full rows=13 cols=6 ['S11', 'S12', 'S13']
semi rows= 2 cols=2 ['S01', 'S07']
anti rows= 1 cols=2 ['S13']
how= Rows Columns SQL
"inner" (default) keys in both both INNER JOIN
"left", "right" every row of one side both; nulls where no match LEFT JOIN, RIGHT JOIN
"full" every row of both both; coalesce=True merges the keys FULL OUTER JOIN
"semi" left rows with a match, once each left only WHERE EXISTS
"anti" left rows without a match left only WHERE NOT EXISTS
"cross" every pair (no on) both CROSS JOIN
Option Use
on="k", on=["a", "b"], left_on=, right_on= key columns, same or different names
validate="m:1", "1:1", "1:m" raise ComputeError when keys are not unique as stated
maintain_order="left" keep the left row order (default: no guaranteed order)
suffix="_store" rename clashing right columns (default _right)
coalesce=True one key column instead of k and k_right (outer joins)
nulls_equal=True let null keys match each other
df.join_asof(o, on="date", by="k", strategy="backward") nearest earlier key; both frames sorted by on
df.join_where(o, pl.col("d") >= pl.col("start")) join on inequality predicates
dup = pl.concat([stores, stores.head(1)]) # S01 twice
sales.join(dup, on="store_id", validate="m:1") # stops the fan-out
Output
polars.exceptions.ComputeError: join keys did not fulfill m:1 validation

pl.scan_* and df.lazy() return a LazyFrame: a query plan. collect() hands the plan to the optimizer, then runs it. In Polars 2, collect() uses the streaming engine by default, which processes data in batches.

query = (
pl.scan_csv("data/sales.csv", try_parse_dates=True)
.filter(pl.col("order_date").dt.year() == 2024)
.group_by("category")
.agg(revenue=pl.col("revenue").sum().round(2))
.sort("revenue", descending=True)
)
print(type(query).__name__, query.collect_schema())
plan = query.explain() # read it from the bottom up
print([x.strip() for x in plan.splitlines() if "PROJECT" in x or "SELECTION" in x])
print(query.head(3).collect().rows())
Output
LazyFrame Schema({'category': String, 'revenue': Float64})
['PROJECT 3/13 COLUMNS', 'SELECTION: (col("order_date").dt.year() == 2024)']
[('Electronics', 939924.77), ('Home', 397844.84), ('Sports', 299576.31)]
Step Call
start lazy pl.scan_csv(p), pl.scan_parquet("dir/*.parquet"), pl.scan_ndjson(p), df.lazy()
output columns, no work lf.collect_schema(), lf.collect_schema().names()
optimized / written plan lf.explain() / lf.explain(optimized=False)
run lf.collect(); engine="auto" (the default) picks streaming; also "in-memory", "gpu"
peek at a few rows lf.head(5).collect()
run several plans at once pl.collect_all([lf1, lf2])
write without collecting lf.sink_parquet(p), lf.sink_csv(p), lf.sink_ndjson(p)
reuse an eager frame df.lazy()...collect()
Optimization Seen in explain() as
projection pushdown: read only used columns PROJECT 3/13 COLUMNS in the scan
predicate pushdown: filter while reading SELECTION: ... in the scan
slice pushdown: stop after N rows SLICE: ... len: 5 in the scan after head(5)
common subplan elimination one shared CACHE for a frame used twice
(
pl.scan_csv("data/sales.csv", try_parse_dates=True)
.filter(pl.col("region") == "West")
.sink_parquet("west.parquet") # streams to disk; returns None
)
west = pl.scan_parquet("west.parquet")
print(west.select(pl.len(), pl.col("revenue").sum().round(2)).collect().row(0))
Output
(4722, 822844.57)
Format Eager read Lazy read Write
CSV pl.read_csv(p) pl.scan_csv(p) df.write_csv(p), lf.sink_csv(p)
Parquet pl.read_parquet(p) pl.scan_parquet(p) df.write_parquet(p), lf.sink_parquet(p)
JSON (one document) pl.read_json(p) — df.write_json(p)
NDJSON (one object per line) pl.read_ndjson(p) pl.scan_ndjson(p) df.write_ndjson(p)
Arrow IPC / Feather pl.read_ipc(p) pl.scan_ipc(p) df.write_ipc(p)
Excel pl.read_excel(p) (needs fastexcel; engine="openpyxl" also works) — df.write_excel(p) (needs xlsxwriter)
database pl.read_database(sql, connection=con) — df.write_database("t", connection)
Python objects pl.DataFrame(dict), pl.from_dicts(rows), pl.from_pandas(pdf) — df.to_dicts(), df.rows(), df.to_pandas()
read_csv / scan_csv option Use
try_parse_dates=True ISO date text → Date / Datetime
schema_overrides={"zip": pl.String} force the dtype of some columns
null_values=["", "N/A", "-"] tokens that mean missing
columns=["a", "b"], n_rows=1000 read some columns / the first rows only
infer_schema_length=10_000 infer dtypes from more rows (default 100)
separator=";", decimal_comma=True, encoding="latin1" European and legacy files
glob=True (default) "data/reports/*.csv" reads every match as one table (same column order)
include_file_paths="source" add a column with the file each row came from
import sqlite3
raw = pl.read_json("data/customers.json") # one document with a nested list
people = raw.select(pl.col("customers").explode()).unnest("customers")
print(raw.columns, people.shape)
city = pl.col("address").struct.field("city") # a field of a Struct column
print(people.select("customer_id", "plan", city=city).head(2))
con = sqlite3.connect("file:data/shop.db?mode=ro", uri=True) # read-only
sql = "SELECT region, COUNT(*) AS n FROM stores GROUP BY region ORDER BY region"
print(pl.read_database(sql, connection=con).rows())
con.close()
Output
['exported_at', 'count', 'customers'] (20, 9)
shape: (2, 3)
┌─────────────┬──────────┬─────────┐
│ customer_id ┆ plan ┆ city │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═════════════╪══════════╪═════════╡
│ C00001 ┆ premium ┆ Chicago │
│ C00002 ┆ standard ┆ Denver │
└─────────────┴──────────┴─────────┘
[('East', 3), ('North', 3), ('South', 3), ('West', 3)]
pandas Polars
pd.read_csv(p, parse_dates=["d"]) pl.read_csv(p, try_parse_dates=True)
df.head(), df.shape, df.dtypes df.head(), df.shape, df.schema
df.describe() df.describe()
df["a"], df[["a", "b"]] df["a"], df.select("a", "b")
df[df["a"] > 0], df.query("a > 0") df.filter(pl.col("a") > 0)
df.loc[mask, ["a", "b"]] df.filter(mask).select("a", "b")
df.iloc[0], df.iloc[:5] df.row(0), df.head(5) / df[:5]
df.assign(c=df["a"] * 2), df["c"] = ... df.with_columns(c=pl.col("a") * 2)
df.loc[mask, "a"] = 0 df.with_columns(a=pl.when(mask).then(0).otherwise(pl.col("a")))
np.where(c, x, y), np.select(...) pl.when(c).then(x).otherwise(y), chained .when()
df.rename(columns={"a": "b"}) df.rename({"a": "b"})
df.drop(columns=["a"]) df.drop("a")
df.astype({"a": "float64"}) df.with_columns(pl.col("a").cast(pl.Float64))
df.sort_values("a", ascending=False) df.sort("a", descending=True)
df.nlargest(3, "a") df.top_k(3, by="a")
df.drop_duplicates("k") df.unique("k", keep="first", maintain_order=True)
df.groupby("k").agg(t=("a", "sum")) df.group_by("k").agg(t=pl.col("a").sum())
df.groupby("k").size() df.group_by("k").len()
df.groupby("k")["a"].transform("mean") pl.col("a").mean().over("k")
df.groupby("k")["a"].cumsum() pl.col("a").cum_sum().over("k")
df.groupby("k")["a"].shift() pl.col("a").shift().over("k")
df["a"].rolling(7).mean() pl.col("a").rolling_mean(7)
df.resample("MS", on="d").sum() df.group_by_dynamic("d", every="1mo").agg(...)
df["a"].value_counts() df["a"].value_counts(sort=True)
df.merge(o, on="k", how="left") df.join(o, on="k", how="left")
df.merge(o, how="outer") df.join(o, on="k", how="full", coalesce=True)
pd.concat([a, b]) pl.concat([a, b]) (how="diagonal" for different columns)
df.pivot_table(index="r", columns="c", values="v", aggfunc="sum") df.pivot(on="c", index="r", values="v", aggregate_function="sum")
df.melt(id_vars="k") df.unpivot(index="k")
df["s"].str.upper(), .str.strip() pl.col("s").str.to_uppercase(), .str.strip_chars()
df["d"].dt.day_of_week (Monday = 0) pl.col("d").dt.weekday() - 1
pd.cut(x, bins) pl.when chain; cut is deprecated in Polars 2
df.isna().sum() df.null_count()
df.fillna(0), df.dropna() df.fill_null(0), df.drop_nulls()
df.ffill() df.fill_null(strategy="forward")
df.set_index("k"), df.reset_index() not needed: there is no index
df.apply(f, axis=1) an expression; map_elements only as a last resort
df.to_numpy() df.to_numpy()
import pandas as pd
pdf = products.head(3).select("product_id", "unit_price").to_pandas() # needs pyarrow
print(type(pdf).__name__, pdf.dtypes.astype(str).tolist())
back = pl.from_pandas(pdf)
print(back.schema)
Output
DataFrame ['str', 'float64']
Schema({'product_id': String, 'unit_price': Float64})

Many tutorials still show Polars 0.x or 1.x code. In Polars 2 most old names raise an error that names the replacement.

Old code Polars 2 What the old code does now
df.groupby(...) df.group_by(...) AttributeError
df.melt(id_vars=...) df.unpivot(index=..., on=...) AttributeRemovedError
df.with_row_count() df.with_row_index() (column index, not row_nr) AttributeRemovedError
pl.count() for rows pl.len(); pl.count("x") counts non-null values TypeError
df.group_by(k).count() df.group_by(k).len() AttributeRemovedError
df.frame_equal(o) df.equals(o) AttributeError
.apply(f), .map_dict(d) .map_elements(f, return_dtype=...), .replace(d) / .replace_strict(d) AttributeError
.where(cond) on an expression .filter(cond) AttributeRemovedError
.flatten() .list.explode() AttributeRemovedError
.str.strip() .str.strip_chars() AttributeError
.str.concat("-") .str.join("-") (default separator "") AttributeRemovedError
rolling_mean(7, min_periods=1) rolling_mean(7, min_samples=1) ArgumentRemovedError
how="outer" how="full" ValueError
join_nulls=True nulls_equal=True ArgumentRemovedError
pivot(columns=...) pivot(on=...) ArgumentRemovedError
collect(streaming=True) collect(engine="streaming"); the default engine is now streaming ArgumentRemovedError
lf.fetch(n) lf.head(n).collect() AttributeRemovedError
lf.profile() removed; time collect() yourself AttributeRemovedError
lf.with_context(o) pl.concat([a, b], how="horizontal") AttributeRemovedError
pl.read_csv_batched(p) pl.scan_csv(p) + collect() AttributeRemovedError
.dt.with_time_unit("ms") cast to pl.Int64, then to the new dtype AttributeRemovedError
df.approx_n_unique() df.select(pl.all().approx_n_unique()) AttributeRemovedError
.cut(breaks), .qcut(q) .bin_intervals(...), .bin_quantiles(...) (both experimental) DeprecationWarning
pl.col("x").is_in(series) pl.col("x").is_in(series.implode()), or a list DeprecationWarning
lf.columns, lf.schema lf.collect_schema().names(), lf.collect_schema() PerformanceWarning
sales.melt(id_vars="order_id") # old tutorial code
Output
polars.exceptions.AttributeRemovedError: `melt` was removed in version 2.0; use `DataFrame.unpivot` instead, with `index` instead of `id_vars` and `on` instead of `value_vars`
Trap Symptom Fix
printing a group_by, unique or join result the row order changes between runs .sort(...), maintain_order=True, or maintain_order="left" for joins
a string in then("bulk") ColumnNotFoundError: unable to find column "bulk" then(pl.lit("bulk")); strings are column names
a column used in the with_columns call that creates it ColumnNotFoundError chain a second with_columns
pl.col("a") > 0 & pl.col("b") > 0 TypeError about the truth value of an Expr parentheses around each comparison, or commas in filter
a CSV read without try_parse_dates=True dates are str; .dt raises InvalidOperationError try_parse_dates=True or .str.to_date(fmt)
print(lazy_frame) a plan, not data lf.collect() or lf.head(5).collect()
collect() after every step slow; the optimizer sees only small pieces build the whole chain, collect once
sort("x").head(3) with ties in x the third row changes between runs add a tie-breaker: sort("x", "id")
rank() with ties for “top N” ranks like 1.5; <= 1 drops both tied rows rank("ordinal") or rank("min")
shift, diff, pct_change without an order values compared across groups or in file order .over("k", order_by="date"), or sort first
df1 == df2 a frame of Booleans df1.equals(df2) (ignores dtypes) or assert_frame_equal (checks them)
counts compared with pandas dtype mismatch u32 vs int64 .cast(pl.Int64) before comparing
big floats 3.5965e6 hides the cents pl.Config.set_fmt_float("full") and .round(2)
map_elements for arithmetic PolarsInefficientMapWarning; a slow Python loop write an expression
NaN vs null fill_null leaves NaN in a float column .fill_nan(None) first, or .fill_nan(0)
.str.contains("1.5") . matches any character literal=True
join on a non-unique right key rows multiply; totals inflate validate="m:1", or aggregate the right side first
Parquet dates sales_sample.parquet stores order_date as Datetime, not Date .dt.date() or .cast(pl.Date)
pivot output names pl.col(2024) fails pivot column names are strings: pl.col("2024")
a glob of CSVs whose columns are in a different order ComputeError: schema names differ pl.concat([pl.read_csv(f) for f in files], how="diagonal_relaxed")
tutorial code from Polars 0.x / 1.x AttributeRemovedError, ArgumentRemovedError see Polars 2 changes

Matplotlib draws static charts (PNG, SVG, PDF) with full control of every element. Seaborn and DataFrame.plot are built on it, so the same fig and ax methods fine-tune their charts too. This page covers the object-oriented API, layouts, plot types, text, styling and saving. Examples use data/sales.csv and data/customers.csv.

I want to… Use… Example
start a chart plt.subplots() fig, ax = plt.subplots(figsize=(7, 4))
a grid of charts plt.subplots(r, c) fig, axs = plt.subplots(2, 2, sharex=True, layout="constrained")
an uneven layout plt.subplot_mosaic fig, axd = plt.subplot_mosaic([["a", "a"], ["b", "c"]])
loop over a grid axs.flat for ax in axs.flat: ax.grid(alpha=0.3)
a line ax.plot ax.plot(x, y, marker="o", label="2024")
points ax.scatter ax.scatter(x, y, s=10, alpha=0.3, c=z, cmap="viridis")
bars ax.bar, ax.barh ax.barh(names, values)
grouped bars ax.grouped_bar (3.11, provisional) ax.grouped_bar(df, tick_labels=df.index)
stacked bars bottom= ax.bar(x, b, bottom=a)
a histogram ax.hist ax.hist(v, bins=30, density=True)
box plots ax.boxplot ax.boxplot(groups, tick_labels=names)
an ECDF ax.ecdf ax.ecdf(v)
a band around a line ax.fill_between ax.fill_between(x, lo, hi, alpha=0.2)
a matrix as colors ax.imshow + fig.colorbar fig.colorbar(ax.imshow(m, cmap="viridis"), ax=ax)
title and labels at once ax.set ax.set(title="...", xlabel="...", ylabel="...", ylim=(0, None))
one title for a grid fig.suptitle, fig.supxlabel fig.suptitle("Q4 review")
a legend ax.legend ax.legend(title="Channel", frameon=False, ncols=2)
a legend outside the plot bbox_to_anchor ax.legend(loc="upper left", bbox_to_anchor=(1, 1))
custom tick labels ax.set_xticks(pos, labels=...) ax.set_xticks(range(1, 13), labels=calendar.month_abbr[1:])
120k on the axis FuncFormatter ax.yaxis.set_major_formatter(FuncFormatter(lambda v, p: f"{v/1e3:.0f}k"))
a percent axis PercentFormatter PercentFormatter(xmax=1) for rates 0–1
short date labels ConciseDateFormatter mdates.ConciseDateFormatter(ax.xaxis.get_major_locator())
a log axis ax.set_yscale("log") or ax.semilogy(...)
values on bars ax.bar_label ax.bar_label(bars, fmt="{:,.0f}")
a reference line ax.axhline, ax.axvline, ax.axline ax.axhline(mean, linestyle=":")
shade a range ax.axvspan, ax.axhspan ax.axvspan(10.5, 12.5, alpha=0.15)
an arrow with text ax.annotate ax.annotate("peak", xy=(x, y), xytext=(tx, ty), arrowprops={"arrowstyle": "->"})
text at a data point ax.text ax.text(x, y, "label", ha="center")
hide the top and right frame ax.spines ax.spines[["top", "right"]].set_visible(False)
a style for one chart plt.style.context with plt.style.context("petroff10"): ...
change one default plt.rcParams, plt.rc_context plt.rcParams["font.size"] = 11
a colormap object matplotlib.colormaps matplotlib.colormaps["viridis"]
a quick chart from pandas df.plot, s.plot.barh df.plot(x="month", y=["a", "b"], ax=ax)
save a file fig.savefig fig.savefig("output/chart.png", dpi=200, bbox_inches="tight")
free memory in a loop plt.close(fig) plt.close("all") closes every figure
Object What it is Get it with
Figure the whole image: size, background, saving fig, ax = plt.subplots(), ax.figure, plt.gcf()
Axes one plot area with its own x and y axes ax, axs[r, c], axd["name"], fig.axes, plt.gca()
Axis the x or y axis: ticks, labels, formatters ax.xaxis, ax.yaxis
Artist anything drawn: lines, bars, text returned by ax.plot, ax.bar; also ax.lines, ax.patches, ax.texts

pyplot (plt.plot) draws on the current Axes; the object-oriented API (ax.plot) names the Axes. Use the object-oriented API in scripts, functions and grids.

pyplot Object-oriented
plt.plot, plt.bar, plt.hist, plt.scatter ax.plot, ax.bar, ax.hist, ax.scatter
plt.title, plt.xlabel, plt.ylabel ax.set_title, ax.set_xlabel, ax.set_ylabel (or one ax.set(...))
plt.xlim, plt.ylim, plt.xticks, plt.yticks ax.set_xlim, ax.set_ylim, ax.set_xticks, ax.set_yticks
plt.legend, plt.grid, plt.text ax.legend, ax.grid, ax.text
plt.savefig fig.savefig
import matplotlib.pyplot as plt
fig, ax = plt.subplots() # one Axes, not an array
fig2, axs = plt.subplots(2, 3) # a 2-D NumPy array of Axes
print(type(ax).__name__, axs.shape, axs[1, 2] is axs.flat[5])
fig3, row = plt.subplots(1, 3) # one row: a 1-D array, so row[1], not row[0, 1]
print(row.shape, ax.figure is fig, len(fig2.axes))
plt.close("all") # close figures you do not show
Output
Axes (2, 3) True
(3,) True 6
Option Effect
figsize=(7, 4) size in inches; pixels = inches × dpi
layout="constrained" no overlapping labels, titles or colorbars; prefer it to fig.tight_layout()
sharex=True, sharey="row" same limits on all panels (or per row/column)
width_ratios=[3, 1], height_ratios=[2, 1] uneven column widths or row heights
squeeze=False always a 2-D array, even for subplots(1, 3)
plt.subplot_mosaic([["a", "a"], ["b", "c"]]) named panels; "." leaves a gap; returns a dict
fig.subfigures(1, 2) independent groups of panels, each with its own suptitle
ax.twinx() a second y-axis on the right; two scales on one chart often mislead
ax.inset_axes([0.6, 0.6, 0.35, 0.35]) a small chart inside an Axes (fractions of the Axes)
ax.set_axis_off() hide an unused panel in a grid
import pandas as pd
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
monthly = sales.resample("MS", on="order_date")["revenue"].sum() / 1000
by_cat = sales.groupby("category")["revenue"].sum().sort_values() / 1000
fig, axd = plt.subplot_mosaic([["trend", "trend"], ["cat", "hist"]],
figsize=(8, 5.5), layout="constrained")
axd["trend"].plot(monthly.index, monthly.to_numpy(), marker="o")
axd["trend"].set(title="Monthly revenue (k USD)", ylim=(0, None))
axd["cat"].barh(by_cat.index, by_cat.to_numpy()) # sorted: largest on top
axd["cat"].set(title="Revenue by category (k USD)")
axd["hist"].hist(sales["revenue"], bins=40, log=True) # log counts: long tail
axd["hist"].set(title="Order line revenue (USD)", ylabel="lines (log)")
print(sorted(axd), f"{monthly.max():.0f}k in {monthly.idxmax():%b %Y}")
plt.show()
Output
['cat', 'hist', 'trend'] 303k in Dec 2024
Three panels: monthly revenue for 2023–2024 mostly runs between 77k and 170k USD with December peaks of 241k and 303k; Electronics leads category revenue with about 1,800k USD, far ahead of Home, Sports, Clothing, Beauty and Books; order-line revenue on a log count scale has 95% of lines below 1,000 USD and a long tail up to about 5,200 USD.
subplot_mosaic: a wide trend panel above two smaller panels.
Method Chart Key options
ax.plot(x, y) line marker="o", linestyle="--", linewidth=2, color="C1", label=
ax.step(x, y, where="mid"), ax.stairs(h, edges) step line for counts per bin or piecewise values
ax.scatter(x, y) points s= size, c= values + cmap=, alpha=, marker=
ax.bar(x, h), ax.barh(y, w) bars width=0.8, bottom= (stack), yerr=, capsize=4, color=
ax.grouped_bar(heights, tick_labels=...) grouped bars (3.11+) a DataFrame (index = groups, columns = series), a dict or a list
ax.hist(v, bins=30) histogram bins= int or edges, density=True, histtype="step", log=True
ax.boxplot(groups) box plot tick_labels=, orientation="horizontal", showfliers=False
ax.violinplot(groups) violin showmedians=True, orientation=, side="low"
ax.ecdf(v) cumulative distribution complementary=True
ax.errorbar(x, y, yerr=e) points with error bars fmt="o", capsize=4
ax.fill_between(x, lo, hi) band, area alpha=0.2, where=
ax.stackplot(x, ys, labels=...) stacked area parts of a whole over time
ax.pie(v, labels=...) pie autopct="%1.0f%%"; prefer sorted bars
ax.hexbin(x, y, gridsize=30) 2-D density mincnt=1, cmap=
ax.imshow(m), ax.pcolormesh(X, Y, Z) matrix, grid cmap=, vmin=, vmax=, aspect="auto"
ax.contour(X, Y, Z), ax.contourf(...) contour lines, filled levels=10
ax.axline((x0, y0), slope=m) infinite straight line for y = x reference lines

DataFrame.plot calls these methods for you: df.plot(kind=...) with "line", "bar", "barh", "hist", "box", "kde", "area", "pie", "scatter", "hexbin". It returns an Axes, so pass ax=ax to draw into a grid and finish with the ax methods below.

Task Code
title, labels, limits ax.set(title="...", xlabel="...", ylabel="...", xlim=(0, 10), ylim=(0, None))
bold left-aligned title ax.set_title("...", loc="left", fontweight="bold")
legend ax.legend(title="Year", loc="upper left", frameon=False, ncols=2)
legend for a whole figure fig.legend(loc="outside right upper") (needs layout="constrained")
no legend entry label="_nolegend_" or no label=
rotate tick labels ax.tick_params(axis="x", labelrotation=45)
fewer ticks ax.xaxis.set_major_locator(MaxNLocator(5))
one tick per month ax.xaxis.set_major_locator(mdates.MonthLocator())
grid behind the data ax.grid(axis="y", alpha=0.3); ax.set_axisbelow(True)
reverse an axis ax.invert_yaxis() (top-to-bottom bar ranking)
margins ax.margins(x=0) (no gap at the ends of a line)
text in Axes coordinates ax.text(0.02, 0.95, "n = 5,000", transform=ax.transAxes)
math in labels ax.set_xlabel(r"$\sigma$ (mm/s)")
Formatter Shows Set with
FuncFormatter(lambda v, pos: ...) anything you compute ax.yaxis.set_major_formatter(...)
StrMethodFormatter("{x:,.0f}") a format string; the field is always x ax.yaxis.set_major_formatter("{x:,.0f}") (a string works too)
PercentFormatter(xmax=1, decimals=0) 25% for 0.25 xmax=100 (default) for values already in percent
EngFormatter(unit="B") SI prefixes: 1.5 kB, 2 MB
mdates.DateFormatter("%b %Y") dates with a strftime pattern ax.xaxis.set_major_formatter(...)
mdates.ConciseDateFormatter(locator) short dates, the year once pair with mdates.AutoDateLocator()
from matplotlib.ticker import EngFormatter, FuncFormatter, StrMethodFormatter
k = FuncFormatter(lambda v, pos: f"{v / 1000:,.0f}k")
comma = StrMethodFormatter("{x:,.0f}")
eng = EngFormatter(places=1)
for value in [950, 241_098, 1_808_108]: # call a formatter as f(value, pos)
print(f"{k(value, 0):>7} {comma(value, 0):>10} {eng(value, 0):>8}")
Output
1k 950 950.0
241k 241,098 241.1 k
1,808k 1,808,108 1.8 M
import calendar
from matplotlib.ticker import FuncFormatter
y2024 = sales[sales["order_date"].dt.year == 2024]
pivot = y2024.pivot_table(index=y2024["order_date"].dt.month, columns="channel",
values="revenue", aggfunc="sum")
fig, ax = plt.subplots(figsize=(7.5, 4), layout="constrained")
for channel in pivot.columns:
ax.plot(pivot.index, pivot[channel], marker="o", label=channel)
ax.axvspan(10.5, 12.5, color="0.5", alpha=0.15) # shade the holiday season
peak = pivot["store"].idxmax()
ax.annotate(f"store peak {pivot['store'].max() / 1000:.0f}k",
xy=(peak, pivot["store"].max()), xytext=(8, 170_000),
arrowprops={"arrowstyle": "->", "color": "0.3"})
ax.set_xticks(range(1, 13), labels=calendar.month_abbr[1:])
ax.yaxis.set_major_formatter(FuncFormatter(lambda v, pos: f"{v / 1000:.0f}k"))
ax.set(title="2024 revenue by channel (USD)", ylim=(0, 180_000))
ax.spines[["top", "right"]].set_visible(False)
ax.legend(title="Channel", frameon=False)
print(pivot.round(-3).astype(int).loc[[1, 11, 12]])
plt.show()
Output
channel online store
order_date
1 42000 78000
11 154000 115000
12 147000 156000
Two lines of 2024 monthly revenue: store revenue stays near 60k to 90k and online revenue near 42k to 70k through September; inside the shaded November–December band online jumps to 154k and store climbs to an annotated peak of 156k in December; the y-axis starts at 0k.
Labels, a formatter, a shaded season, an annotation and a legend.
import matplotlib
print(len(plt.style.available), [s for s in plt.style.available if "petroff" in s])
print(matplotlib.colormaps["viridis"].N, "colors in viridis") # registry of colormaps
with plt.rc_context({"font.size": 12, "axes.spines.top": False}): # temporary
print(plt.rcParams["font.size"])
print(plt.rcParams["font.size"]) # back to the default
Output
28 ['petroff10', 'petroff6', 'petroff8']
256 colors in viridis
12.0
10.0
Tool Scope Example
plt.style.use("petroff10") rest of the program at the top of a script
with plt.style.context("ggplot"): one block one chart in a different style
plt.rcParams["key"] = value rest of the program plt.rcParams["axes.grid"] = True
with plt.rc_context({...}): one block {"font.size": 12}
matplotlibrc file or style.mplstyle a project plt.style.use("./style.mplstyle")
rcParams key Example value
figure.figsize, figure.dpi (7, 4), 100
savefig.dpi, savefig.bbox 200, "tight"
font.size, axes.titlesize, axes.titleweight 11, "large", "bold"
axes.spines.top, axes.spines.right False
axes.grid, grid.alpha True, 0.3
axes.prop_cycle plt.cycler(color=["#0173b2", "#de8f05", "#029e73"])
Color input Meaning
"C0" … "C9" the nth color of the current cycle
"tab:blue", "steelblue" named colors
"#D55E00", (0.2, 0.4, 0.6) hex or RGB (0–1)
"0.7" a gray: "0" black, "1" white
cmap="viridis", "cividis", "magma" sequential: magnitudes
cmap="RdBu_r", "coolwarm" with vmin=-v, vmax=v diverging: signs, correlations
cmap="tab10", style petroff10, tableau-colorblind10 qualitative, color-blind friendly
name + "_r" reversed colormap
regions = sales.pivot_table(index="region", columns="channel", values="revenue",
aggfunc="sum") / 1000
with plt.style.context("petroff10"): # a color-blind-friendly cycle
fig, ax = plt.subplots(figsize=(7, 3.8), layout="constrained")
bars = ax.grouped_bar(regions, tick_labels=regions.index, labels=regions.columns)
for container in bars.bar_containers:
ax.bar_label(container, fmt="{:.0f}", fontsize=8)
ax.set(title="Revenue by region and channel, 2023–2024 (k USD)", ylim=(0, 650))
ax.legend(frameon=False, ncols=2)
print(regions.round(0))
plt.show()
Output
channel online store
region
East 426.0 567.0
North 378.0 511.0
South 384.0 508.0
West 332.0 491.0
Grouped bars for four regions with values on top: store revenue beats online in every region, from 567k vs 426k in East to 491k vs 332k in West; North and South are close at about 510k store and 380k online.
grouped_bar with bar_label, drawn in the petroff10 style.
savefig option Effect
extension .png, .svg, .pdf raster or vector; the format follows the name
dpi=200 pixels per inch for raster: 7 × 4 in at 200 → 1400 × 800 px
bbox_inches="tight", pad_inches=0.1 crop to the content; keeps labels that stick out
transparent=True no background
facecolor="white" a solid background (for dark themes)
metadata={"Title": "..."} file metadata (PNG, PDF, SVG)
from pathlib import Path
Path("output").mkdir(exist_ok=True)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot([1, 2, 3], [3, 1, 2])
fig.savefig("output/line.png", dpi=200) # no bbox_inches: exact pixel size
fig.savefig("output/line.svg") # vector: sharp at any size
print(plt.imread("output/line.png").shape) # rows, columns, RGBA
plt.close(fig) # free memory when you save in a loop
Output
(800, 1400, 4)

Several charts in one PDF: from matplotlib.backends.backend_pdf import PdfPages, then with PdfPages("output/report.pdf") as pdf: pdf.savefig(fig) for each figure.

Trap Symptom Fix
ax.title("...") TypeError: 'Text' object is not callable ax.set_title("...") or ax.set(title=...)
plt.subplots(1, 3) then axs[0, 1] IndexError: too many indices one row gives a 1-D array: axs[1]; or squeeze=False
ax.boxplot(..., labels=[...]) TypeError: ... unexpected keyword argument 'labels' in 3.11 tick_labels=[...]
vert=False in boxplot or violinplot MatplotlibDeprecationWarning in 3.11 orientation="horizontal"
matplotlib.cm.get_cmap("viridis") AttributeError (removed in 3.9) matplotlib.colormaps["viridis"]
plt.savefig after plt.show() an empty image save first, then show
many plt.subplots in a loop rising memory; RuntimeWarning: More than 20 figures have been opened plt.close(fig) after saving
labels overlap in a grid cut or overlapping titles layout="constrained"
plt.style.use in a library or notebook cell every later chart changes with plt.style.context(...)
a bar chart not starting at 0 small differences look huge ax.set_ylim(0, None) for bars
PercentFormatter() on rates 0–1 0.25 shows as 0% PercentFormatter(xmax=1)
x values not sorted a line zigzags back and forth sort by x first, or use ax.scatter
ax.plot with a pandas Period index TypeError: float() argument must be a string or a real number, not 'Period' idx.to_timestamp(), or .astype(str) for labels
jet or rainbow colormap false edges; not color-blind safe viridis, cividis, or a diverging map
twinx with two unrelated scales readers compare heights that do not compare two panels with sharex=True
plt.show() on a server or in CI (MPLBACKEND=Agg) nothing appears; UserWarning: FigureCanvasAgg is non-interactive fig.savefig(...) instead of show

Seaborn draws statistical charts from a DataFrame and column names: it groups, aggregates, adds confidence intervals and builds legends for you. It draws with Matplotlib, so every ax method from the Matplotlib page works on its charts. Examples use data/customers.csv and data/sensors.csv.

I want to… Use… Example
a theme for every chart sns.set_theme sns.set_theme(style="whitegrid", palette="colorblind")
the distribution of a column sns.histplot sns.histplot(data=df, x="price", bins=30)
a skewed column log_scale=True sns.histplot(data=df, x="price", log_scale=True)
compare distributions of groups hue= + stat="density", common_norm=False sns.histplot(data=df, x="age", hue="churned", stat="density", common_norm=False)
a smooth density sns.kdeplot sns.kdeplot(data=df, x="price", hue="area", fill=True)
cumulative shares sns.ecdfplot sns.ecdfplot(data=df, x="price", hue="area")
the mean per group with a CI sns.barplot, sns.pointplot sns.barplot(data=df, x="plan", y="churned", errorbar=("ci", 95))
counts per category sns.countplot sns.countplot(data=df, y="plan", order=["basic", "standard", "premium"])
distributions per group sns.violinplot, sns.boxenplot, sns.stripplot sns.violinplot(data=df, x="plan", y="charges", inner="quart")
two halves of a violin split=True with a 2-level hue sns.violinplot(..., hue="churned", split=True)
a scatter with color, size and marker sns.scatterplot sns.scatterplot(data=df, x="a", y="b", hue="g", size="n", style="kind")
a mean line with a band sns.lineplot sns.lineplot(data=df, x="month", y="sales", hue="year")
one line per unit, no aggregation units=, estimator=None sns.lineplot(..., units="sensor_id", estimator=None)
a fitted line sns.regplot, sns.lmplot sns.regplot(data=df, x="sqft", y="price", scatter_kws={"alpha": 0.3})
check a fit’s residuals sns.residplot sns.residplot(data=df, x="sqft", y="price", lowess=True)
a table as colors sns.heatmap sns.heatmap(pivot, annot=True, fmt=".0%", cmap="rocket_r")
a correlation matrix sns.heatmap with vmin=-1, vmax=1 sns.heatmap(corr, cmap="vlag", vmin=-1, vmax=1, annot=True)
clustered rows and columns sns.clustermap sns.clustermap(corr, cmap="vlag")
one panel per group figure-level + col=, row= sns.relplot(..., col="region", col_wrap=2)
draw into my Matplotlib grid axes-level + ax= sns.histplot(..., ax=axs[0])
two variables and their margins sns.jointplot sns.jointplot(data=df, x="a", y="b", kind="hex")
all pairs of a few columns sns.pairplot sns.pairplot(df[cols].sample(300, random_state=42), corner=True)
a fixed category order order=, hue_order=, col_order= order=["basic", "standard", "premium"]
one color, no legend color= sns.barplot(..., color="C0")
a palette for categories hue= + palette= sns.barplot(data=df, x="plan", y="v", hue="plan", palette="Set2", legend=False)
move the legend sns.move_legend sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1))
remove the top and right frame sns.despine sns.despine(), sns.despine(left=True)
bigger fonts for slides sns.set_theme(context=...) context="talk"
save a figure-level chart g.savefig g.savefig("output/grid.png", dpi=150)
Family Axes-level (ax=) Figure-level (col=, row=) Key parameters
distribution histplot, kdeplot, ecdfplot, rugplot displot(kind="hist" | "kde" | "ecdf") bins, binwidth, stat, common_norm, multiple, element, log_scale, bw_adjust, cumulative
categorical: estimates barplot, pointplot, countplot catplot(kind="bar" | "point" | "count") estimator, errorbar, n_boot, seed, order, dodge
categorical: distributions boxplot, violinplot, boxenplot catplot(kind="box" | "violin" | "boxen") inner, split, cut, density_norm, gap, fill
categorical: points stripplot, swarmplot catplot(kind="strip" | "swarm") jitter, dodge, size, alpha
relational scatterplot, lineplot relplot(kind="scatter" | "line") hue, size, style, sizes, markers, estimator, errorbar, units
regression regplot, residplot lmplot order, logistic, lowess, robust, ci, x_bins, scatter_kws, line_kws
matrix heatmap clustermap annot, fmt, cmap, vmin, vmax, mask, linewidths, cbar, square
multi-plot — pairplot, jointplot, FacetGrid, PairGrid, JointGrid vars, hue, corner, kind, diag_kind, height, aspect
Parameter Values Meaning
stat (histplot) "count", "frequency", "density", "probability", "percent" what bar height means
common_norm True (default), False normalize all hue groups together or each on its own
multiple "layer", "stack", "dodge", "fill" how hue groups combine; "fill" = 100% stacked
element "bars", "step", "poly" histogram shape; "step" overlaps well
errorbar ("ci", 95), "se", "sd", ("pi", 50), None interval: bootstrap CI, standard error, standard deviation, percentile
estimator "mean" (default), "median", "sum", a function what one bar or line point shows
inner (violinplot) "box", "quart", "point", "stick", None what is drawn inside each violin
native_scale True keep numeric or date x positions in categorical plots
legend "auto", "brief", "full", False legend detail; False hides it
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
sns.set_theme(style="whitegrid", palette="colorblind") # global: every later chart
customers = pd.read_csv("data/customers.csv")
plans = ["basic", "standard", "premium"]
fig, axs = plt.subplots(1, 2, figsize=(9, 3.6), layout="constrained")
sns.histplot(data=customers, x="monthly_charges", hue="plan", hue_order=plans,
element="step", bins=40, ax=axs[0]) # axes-level: draws into axs[0]
sns.barplot(data=customers, x="contract", y="churned", hue="plan", hue_order=plans,
order=["month-to-month", "one-year", "two-year"],
errorbar=("ci", 95), seed=42, ax=axs[1]) # mean of 0/1 = churn rate
axs[0].set(xlabel="monthly charges (USD)")
axs[1].set(ylabel="churn rate")
axs[1].get_legend().remove() # one legend is enough
print(customers.pivot_table(index="contract", columns="plan", values="churned")
.loc[:, plans].round(3))
plt.show()
Output
plan basic standard premium
contract
month-to-month 0.265 0.262 0.432
one-year 0.064 0.049 0.214
two-year 0.028 0.026 0.052
Left: step histograms of monthly charges form three separate humps by plan, basic near 38 USD, standard near 63 USD and premium near 97 USD. Right: churn-rate bars with 95% error bars: month-to-month churn is about 26% for basic and standard and 43% for premium; one-year churn is 5–6% except 21% for premium; two-year churn stays at 5% or below.
Two axes-level functions in one Matplotlib grid.
Axes-level Figure-level
Functions histplot, barplot, scatterplot, heatmap, … displot, catplot, relplot, lmplot, pairplot, jointplot, clustermap
Returns a Matplotlib Axes a FacetGrid (or PairGrid, JointGrid, ClusterGrid)
Where it draws the current Axes or ax= its own new figure
Panels one col=, row=, col_wrap=
Size plt.subplots(figsize=...) height= (inches per panel), aspect= (width ÷ height)
Legend inside the Axes outside, on the right
Fine-tune ax.set(...) g.set(...), g.set_titles(...), g.axes.flat, g.figure
FacetGrid method or attribute Does
g.set_titles("{col_name}"), "{row_name} | {col_name}" short panel titles
g.set_axis_labels("x label", "y label") labels on the outer panels
g.set(xlim=(0, 100), yscale="log") ax.set(...) on every panel
g.figure.suptitle("...", y=1.03) one title above the grid
g.axes, g.axes.flat, g.axes_dict["premium"] the panels as an array, a flat iterator or a dict
g.map_dataframe(func, x=..., y=...) run any plotting function on each panel’s subset
g.refline(y=0.5) a reference line on every panel
g.tick_params(axis="x", labelrotation=45) ticks on every panel
g.legend, sns.move_legend(g, "upper center", ncols=3) the legend, or move it
g.savefig("output/x.png", dpi=150) save the whole figure
Argument Maps a column to Works in
hue= color almost every function
size= marker size or line width scatterplot, lineplot, relplot
style= marker shape or dash pattern scatterplot, lineplot, relplot
col=, row= separate panels figure-level functions
col_wrap=3 wrap columns onto rows figure-level functions, with col= only
units= one unaggregated line per unit lineplot, relplot(kind="line")
x= and y= swapped horizontal categorical plots sns.barplot(data=df, x="value", y="category")

A numeric hue gets a continuous light-to-dark palette; a text hue gets distinct colors. Convert with df["year"].astype(str) when the numbers are labels.

labels = {0: "stayed", 1: "churned"}
status = customers.assign(status=customers["churned"].map(labels)) # readable legend
g = sns.catplot(data=status, kind="violin", x="plan", y="monthly_charges",
hue="status", hue_order=["stayed", "churned"], split=True,
inner="quart", col="contract",
order=plans, col_order=["month-to-month", "one-year", "two-year"],
height=3, aspect=0.9) # figure-level: returns a FacetGrid
g.set_titles("{col_name}")
g.set_axis_labels("", "monthly charges (USD)")
print(type(g).__name__, g.axes.shape, sorted(g.axes_dict))
plt.show()
Output
FacetGrid (1, 3) ['month-to-month', 'one-year', 'two-year']
Three panels of split violins of monthly charges by plan, one panel per contract, with stayed customers on the left half and churned customers on the right half, as the status legend shows; charges center near 38, 63 and 97 USD for basic, standard and premium, and the churned half sits at most a few dollars higher.
catplot with col= for contracts and hue= split violins for churn.

The relational family draws lines and points. relplot(kind="line") averages the rows at each x and draws a bootstrap confidence band around the mean:

sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
sensors["hour"] = sensors["timestamp"].dt.hour
sensors["week"] = (sensors["timestamp"].dt.day <= 7).map({True: "May 1–7",
False: "May 8–14"})
g = sns.relplot(data=sensors, kind="line", x="hour", y="temperature_c",
hue="sensor_id", col="week", errorbar=("ci", 95), seed=42,
height=3, aspect=1.4) # band: 95% bootstrap CI of the mean
g.set_titles("{col_name}")
g.set_axis_labels("hour of day", "temperature (°C)")
g.legend.set_title("sensor")
print(sensors.groupby(["week", "sensor_id"])["temperature_c"].mean().unstack().round(1))
plt.show()
Output
sensor_id S1 S2 S3 S4
week
May 1–7 22.1 24.6 22.3 26.0
May 8–14 22.0 24.6 24.7 26.1
Two panels of mean temperature by hour of day for sensors S1 to S4, May 1–7 and May 8–14, each with a narrow confidence band: every sensor is coolest around 2–4 a.m. and warmest near 3–4 p.m.; S4 runs warmest (24 to 28 °C) and S1 coolest (20 to 24 °C); S3 tracks S1 in the first week but runs about 2.5 °C warmer in the second week.
relplot(kind="line") with hue= per sensor, col= per week and a 95% bootstrap band.
Call Effect
sns.set_theme() Seaborn defaults: darkgrid style, deep palette, notebook context
sns.set_theme(style=...) "darkgrid", "whitegrid", "dark", "white", "ticks"
sns.set_theme(context=...) font scale: "paper" < "notebook" < "talk" < "poster"
sns.set_theme(palette=..., font_scale=1.2, rc={...}) default colors, size factor, any rcParams
with sns.axes_style("white"): a style for one block
sns.despine(offset=5, trim=True) remove the top and right spines
sns.reset_defaults() Matplotlib defaults again
Palette Kind Use for
"colorblind", "deep", "muted", "Set2", "tab10" qualitative categories without order
"rocket", "mako", "viridis", "crest" sequential counts, rates; add "_r" to reverse
"vlag", "icefire", "RdBu_r" diverging values around a center, correlations
"light:#0173b2", "dark:salmon" sequential from one color one hue from light or dark to that color
"blend:#7AB,#EDA" blend of two or more colors custom sequential ramps
"ch:s=.25,rot=-.25" cubehelix sequential with even brightness steps
print(sns.color_palette("colorblind", 3).as_hex()) # a list of colors
print(sns.color_palette("light:#0173b2", 3).as_hex()) # a ramp from one color
cmap = sns.color_palette("rocket", as_cmap=True) # a Matplotlib colormap
print(type(cmap).__name__, cmap.N)
Output
['#0173b2', '#de8f05', '#029e73']
['#eff1f3', '#78b2d2', '#0173b2']
ListedColormap 256
daily = sensors.pivot_table(index="sensor_id", columns=sensors["timestamp"].dt.day,
values="vibration_mm_s", aggfunc="mean")
fig, ax = plt.subplots(figsize=(9, 2.8), layout="constrained")
sns.heatmap(daily, annot=True, fmt=".1f", cmap="rocket_r", linewidths=0.5,
cbar_kws={"label": "mm/s"}, ax=ax) # cmap _r: dark = high
ax.set(xlabel="day of May 2024", ylabel="", title="Mean vibration per sensor and day")
print(daily.loc["S4"].tail(4).round(1).to_dict())
plt.show()
Output
{11: 3.3, 12: 5.2, 13: 6.9, 14: 9.0}
Heatmap of mean daily vibration for sensors S1 to S4 over May 1–14: S1, S2 and S3 stay flat near 2.1, 2.8 and 2.0 mm/s, and S4 stays near 3.2 mm/s until May 11, then darkens to 5.2, 6.9 and 9.0 mm/s on May 12–14.
An annotated heatmap of a pivot table.
Old code or symptom Message Use now
ci=95, ci=None FutureWarning: The ci parameter is deprecated errorbar=("ci", 95), errorbar=None
palette= without hue= in barplot, boxplot, countplot, … FutureWarning: Passing palette without assigning hue is deprecated hue=<the x column>, legend=False, or color="C0"
palette= without hue= in histplot UserWarning: Ignoring palette because no hue variable has been assigned color=
scale= in violinplot FutureWarning: The scale parameter has been renamed density_norm="width" (or "area", "count")
sns.boxplot, catplot(kind="box") with Matplotlib 3.11 MatplotlibDeprecationWarning about vert (from inside Seaborn; hidden by default) ax.boxplot(..., orientation="vertical"), sns.violinplot(inner="box") or sns.boxenplot
sns.heatmap(..., center=0) with Matplotlib 3.11 PendingDeprecationWarning about set_bad (hidden by default) symmetric vmin=-v, vmax=v
g.fig still works g.figure (the documented name)
swarmplot with thousands of points UserWarning: 28.3% of the points cannot be placed stripplot(alpha=0.3) or a sample
seaborn.objects (so.Plot) with pandas 3.1 hidden Pandas4Warning about the copy keyword the function interface, or ignore until a Seaborn fix
sns.load_dataset("tips") needs the internet read the course files in data/

New in 0.13: categorical functions accept native_scale=True, log_scale=, formatter=, fill=False and gap=, and hue= works without dodging when it equals x.

Trap Symptom Fix
ax= passed to a figure-level function a UserWarning, and a second figure appears use the axes-level function, or size with height=/aspect=
figsize for relplot, catplot, displot ignored height= and aspect=
sns.set_theme in a module or notebook every later chart changes style call it once at the top; sns.axes_style in a with block for one chart
categories in data order weekdays, months or plans in random order order=, hue_order=, col_order=
numeric hue such as a year a light-to-dark gradient, not distinct colors hue=df["year"].astype(str)
groups of different size in histplot the small group looks flat stat="density", common_norm=False
barplot on raw rows it shows the mean, not the sum estimator="sum" or aggregate first
bootstrap CIs differ between runs error bars move slightly seed=42
barplot and lineplot are slow CIs bootstrap 1,000 times errorbar=None or errorbar="se"
pairplot on many columns or rows slow and unreadable 3–5 columns and a sample of a few hundred rows
a KDE below 0 for prices or ages density where no data can exist cut=0, clip=(0, None) or histplot
two legends in a grid of axes-level plots repeated legends ax.get_legend().remove() or legend=False on all but one
sns.boxplot in a strict warnings setup MatplotlibDeprecationWarning with Matplotlib 3.11 ax.boxplot(orientation=...) or a violin
annotation arrows invisible in a Seaborn theme the default arrow is white on darkgrid arrowprops={"arrowstyle": "->", "color": "0.3"}
heatmap of a large table with annot=True unreadable numbers fewer rows, or no annot

Plotly draws interactive charts for the browser: hover tooltips, zoom, pan and legend clicks that hide series. Plotly Express (px) builds a whole figure from a DataFrame in one call; fig.update_* methods then change its layout, axes and traces. The result is a plotly.graph_objects.Figure that you show, save as HTML or embed in a web app. Examples use data/sales.csv and data/houses.csv.

I want to… Use… Example
a line chart px.line px.line(df, x="date", y="visits", markers=True)
one line per group color= px.line(df, x="month", y="revenue", color="channel")
bars px.bar px.bar(df, x="region", y="revenue", color="channel", barmode="group")
values on the bars text_auto= px.bar(..., text_auto=".3s") → 427k
a 100% stacked bar barnorm="percent" in the layout fig.update_layout(barnorm="percent")
a scatter with details on hover px.scatter + hover_name, hover_data px.scatter(df, x="sqft", y="price", hover_name="house_id")
bubble size size= px.scatter(..., size="bedrooms", size_max=12)
a trend line trendline= (needs statsmodels) px.scatter(..., trendline="ols") or "lowess"
a histogram px.histogram px.histogram(df, x="price", nbins=50, marginal="box")
a mean per group without aggregating histfunc= px.histogram(df, x="plan", y="churned", histfunc="avg")
distributions per group px.box, px.violin, px.strip, px.ecdf px.box(df, x="area", y="price", points="outliers")
a heatmap of a matrix px.imshow px.imshow(corr, text_auto=".2f", zmin=-1, zmax=1)
a 2-D histogram for many points px.density_heatmap px.density_heatmap(df, x="sqft", y="price")
parts of a whole, hierarchy px.pie, px.sunburst, px.treemap px.treemap(df, path=["category", "product"], values="revenue")
small multiples facet_col=, facet_row= px.histogram(..., facet_col="area", facet_col_wrap=4)
an animation over time animation_frame= + fixed range px.bar(..., animation_frame="month", range_y=[0, top])
nice axis and tooltip names labels= labels={"revenue": "Revenue (USD)"}
a fixed category order category_orders= category_orders={"plan": ["basic", "standard", "premium"]}
fixed colors per category color_discrete_map= color_discrete_map={"online": "#0173b2", "store": "#de8f05"}
a clean background template= template="plotly_white", or px.defaults.template = "plotly_white"
a log axis log_x=, log_y= px.scatter(..., log_y=True)
title, legend, margins fig.update_layout fig.update_layout(title="...", legend_title_text="Channel")
axis format fig.update_yaxes fig.update_yaxes(tickformat=",", rangemode="tozero")
custom tooltip text fig.update_traces(hovertemplate=...) "%{x}: %{y:,.0f} USD<extra></extra>"
one tooltip for all series hovermode= fig.update_layout(hovermode="x unified")
a reference line or band fig.add_hline, fig.add_vrect fig.add_hline(y=5000, line_dash="dash", annotation_text="target")
a text label with an arrow fig.add_annotation fig.add_annotation(x=x, y=y, text="peak")
add a series to a px figure fig.add_scatter, fig.add_trace fig.add_scatter(x=..., y=..., mode="markers", name="...")
a range slider for dates fig.update_xaxes(rangeslider_visible=True)
short facet titles fig.for_each_annotation lambda a: a.update(text=a.text.split("=")[-1])
different traces side by side make_subplots + go traces make_subplots(rows=1, cols=2)
save an interactive chart fig.write_html fig.write_html("output/chart.html", include_plotlyjs="cdn")
an HTML snippet for a web page fig.to_html fig.to_html(full_html=False, include_plotlyjs="cdn")
a PNG or SVG fig.write_image (needs kaleido>=1) fig.write_image("output/chart.png", scale=2)
Family Functions Typical call
trends line, area, scatter px.line(df, x="date", y="visits", color="channel", line_shape="spline")
comparison bar, funnel, timeline px.bar(df, x="value", y="name", orientation="h")
relations scatter, scatter_matrix, parallel_coordinates, scatter_3d px.scatter_matrix(df, dimensions=["sqft", "price"], color="area")
distributions histogram, box, violin, strip, ecdf px.violin(df, x="plan", y="charges", box=True, points=False)
2-D density density_heatmap, density_contour px.density_heatmap(df, x="a", y="b", nbinsx=40)
matrices and images imshow px.imshow(pivot, text_auto=True, aspect="auto")
parts of a whole pie, sunburst, treemap, icicle, funnel_area px.sunburst(df, path=["region", "channel"], values="revenue")
categories flow parallel_categories px.parallel_categories(df, dimensions=["plan", "contract"])
polar, ternary scatter_polar, line_polar, bar_polar, scatter_ternary px.line_polar(df, r="value", theta="axis", line_close=True)
maps scatter_geo, choropleth, scatter_map, density_map, choropleth_map px.choropleth(df, locations="iso3", color="gdp") (the *_mapbox functions are gone in Plotly 7)

Every function takes a DataFrame in long (tidy) format plus column names. Wide data works for line, bar and area too: px.line(wide_df) draws one line per column.

Argument Does Example
color= color by a column; text → distinct colors, numbers → a color scale color="channel"
color_discrete_sequence= colors for categories px.colors.qualitative.Safe (color-blind friendly)
color_discrete_map= an exact color per category {"online": "#0173b2"}
color_continuous_scale= a scale for numeric color "Viridis", "RdBu_r"; with range_color=[0, 1]
symbol=, line_dash=, pattern_shape= marker shape, dash, bar fill pattern symbol="has_pool"
size=, size_max= bubble size size="bedrooms", size_max=15
opacity= transparency for overlapping points opacity=0.5
hover_name= bold first line of the tooltip hover_name="house_id"
hover_data= extra tooltip columns: a list, or a dict of formats {"price": ":$,.0f", "date": "|%Y-%m-%d", "area": False}
custom_data= columns for %{customdata[0]} in a hovertemplate custom_data=["house_id"]
text= a text label on each mark text="product"
labels= rename columns in axes, legend and tooltips labels={"sqft": "Size (sq ft)"}
facet_col=, facet_row= one panel per value facet_col="neighborhood"
facet_col_wrap= panels per row facet_col_wrap=4
facet_col_spacing=, facet_row_spacing= gap between panels 0.04
animation_frame= one frame per value, with a play button and slider animation_frame="month"
animation_group= which marks are the same object across frames animation_group="country"
range_x=, range_y= fixed axis ranges (needed for a stable animation) range_y=[0, 100_000]
category_orders= order of categories, facets and frames {"plan": ["basic", "standard", "premium"]}
log_x=, log_y= log axes log_y=True
barmode= "relative" (stacked, default), "group", "overlay" barmode="group"
title=, template=, width=, height= figure options height=400

hover_data formats use d3 syntax after a colon: ":,.0f" (thousands separator), ":.1%", ":$,.0f". For dates, "|%Y-%m-%d" uses a pipe. False hides a column that would show by default.

import pandas as pd
import plotly.express as px
houses = pd.read_csv("data/houses.csv")
fig = px.scatter(houses, x="sqft", y="price", color="neighborhood",
hover_name="house_id",
hover_data={"price": ":$,.0f", "neighborhood": False})
print(len(fig.data), "traces: one per color") # px makes one trace per group
print(fig.data[0].hovertemplate) # what the tooltip shows
fig = px.histogram(houses, x="price", facet_col="neighborhood", facet_col_wrap=4)
print(fig.layout.annotations[0].text) # default facet title: column=value
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
print(fig.layout.annotations[0].text)
Output
8 traces: one per color
<b>%{hovertext}</b><br><br>sqft=%{x}<br>price=%{y:$,.0f}<extra></extra>
neighborhood=Riverside
Riverside
Method Changes Example
fig.update_layout(...) title, legend, margins, size, fonts, hover fig.update_layout(title="...", height=400, margin={"t": 60})
magic underscores a nested property in one keyword legend_title_text="Channel", xaxis_title="Month", font_size=13
fig.update_xaxes(...), update_yaxes(...) every x or y axis, including facets tickformat=",.0f", tickangle=-45, rangemode="tozero", dtick="M3"
fig.update_yaxes(matches=None) independent y ranges per facet
fig.update_traces(...) every trace, or only some with selector= fig.update_traces(marker_size=6, selector={"mode": "markers"})
fig.update_traces(texttemplate=..., textposition="outside") labels on bars texttemplate="%{y:,.0f}"
fig.add_hline, add_vline a reference line fig.add_vline(x="2024-04-08", line_dash="dot")
fig.add_hrect, add_vrect a shaded band fig.add_vrect(x0=a, x1=b, fillcolor="gray", opacity=0.15, line_width=0)
fig.add_annotation text with an optional arrow fig.add_annotation(x=x, y=y, text="peak", showarrow=True)
fig.add_scatter, add_bar, add_trace(go.X(...)) another series fig.add_scatter(x=d, y=v, mode="lines", name="7-day mean")
fig.update_layout(hovermode=...) "closest", "x", "x unified" hovermode="x unified" for time series
fig.update_layout(legend={...}) legend position legend={"orientation": "h", "y": 1.1}
hovertemplate part Shows
%{x}, %{y} the x and y values
%{y:,.0f}, %{y:.1%}, %{x|%b %Y} formatted values (d3 formats; dates after |)
%{customdata[0]} a column passed with custom_data=
%{hovertext} the hover_name column
<br>, <b>…</b> a line break, bold text
<extra></extra> hide the trace-name box next to the tooltip
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
sales["month"] = sales["order_date"].dt.strftime("%Y-%m")
keys = ["month", "category", "channel"]
monthly = sales.groupby(keys, as_index=False)["revenue"].sum()
top = monthly["revenue"].max()
fig = px.bar(monthly, x="category", y="revenue", color="channel", barmode="group",
animation_frame="month", range_y=[0, top * 1.1], # fixed y across frames
category_orders={"category": ["Electronics", "Home", "Sports",
"Clothing", "Beauty", "Books"]},
labels={"revenue": "Revenue (USD)", "category": "", "channel": "Channel"},
color_discrete_sequence=px.colors.qualitative.Safe,
template="plotly_white", title="Monthly revenue by category, 2023–2024")
fig.update_traces(hovertemplate="%{x}: %{y:,.0f} USD<extra></extra>")
fig.update_yaxes(tickformat=",")
print(len(fig.frames), "frames,", fig.frames[0].name, "to", fig.frames[-1].name)
best = monthly.loc[monthly["revenue"].idxmax()]
print(best["month"], best["category"], best["channel"], round(best["revenue"]))
fig.show()
Output
24 frames, 2023-01 to 2024-12
2024-12 Electronics store 92767
Monthly revenue by category and channel, animated by month · Open the interactive chart in a new tab

Press play or drag the slider to step through the 24 months. Without range_y, each frame rescales its own y-axis and the bars seem to jump. hovertemplate changes the tooltip of the first frame; the frames keep Plotly Express’s default tooltip.

Plotly Express returns a go.Figure. Build one yourself for mixed chart types or a custom grid.

import plotly.graph_objects as go
from plotly.subplots import make_subplots
by_area = houses.groupby("neighborhood")["price"].median().sort_values()
fig = make_subplots(rows=1, cols=2, subplot_titles=["Median price", "Price vs size"])
fig.add_trace(go.Bar(x=by_area.to_numpy(), y=by_area.index, orientation="h"),
row=1, col=1)
fig.add_trace(go.Scatter(x=houses["sqft"], y=houses["price"], mode="markers",
marker={"size": 4, "opacity": 0.4}), row=1, col=2)
fig.update_layout(showlegend=False, template="plotly_white", height=380)
print([trace.type for trace in fig.data], fig.layout.xaxis2.anchor)
Output
['bar', 'scatter'] y2
Graph object Draws
go.Scatter(mode="lines" | "markers" | "lines+markers") lines and points
go.Scattergl the same with WebGL, for 100,000+ points
go.Bar, go.Histogram, go.Box, go.Violin bars and distributions
go.Heatmap, go.Contour grids of values
go.Pie, go.Sunburst, go.Treemap parts of a whole
go.Indicator a big KPI number with a delta
go.Table a table
Call Result
fig.show() opens the chart in a notebook output cell or a browser tab; it saves nothing
fig.write_html("output/c.html", include_plotlyjs="cdn") a small file that loads plotly.js from the web
fig.write_html("output/c.html") a self-contained file (plotly.js embedded, about 4.6 MB) that works offline
fig.to_html(full_html=False, include_plotlyjs="cdn") a <div> string to put into your own page or template
fig.write_image("output/c.png", scale=2) a static image; needs pip install "kaleido>=1" and a Chrome browser
fig.to_json(), plotly.io.from_json(text) the figure as JSON and back
pio.renderers.default = "browser" where fig.show() goes: "notebook", "vscode", "browser", "png"
from pathlib import Path
Path("output").mkdir(exist_ok=True)
fig.write_html("output/houses.html", include_plotlyjs="cdn")
html = Path("output/houses.html").read_text(encoding="utf-8")
print("cdn.plot.ly" in html, html.count("<script")) # the library comes from a CDN
Output
True 3
Trap Symptom Fix
expecting fig.show() to save no file appears fig.write_html(...) or fig.write_image(...)
fig.write_image without kaleido RuntimeError: Image export requires the Kaleido package, v1.0.0 or greater pip install "kaleido>=1" (it uses a local Chrome)
px.scatter_mapbox and other *_mapbox functions AttributeError in Plotly 7 px.scatter_map, px.density_map, px.choropleth_map
titlefont= and other old layout names ValueError: Invalid property specified ... 'titlefont' title_font=... or title={"font": {...}}
reading fig.to_dict() or fig.to_json() arrays appear as {'dtype': 'i1', 'bdata': 'AQI='} read fig.data[0].y (a NumPy array) instead
an animation without range_x/range_y axes rescale on every frame fix the ranges
one long-format column with many categories in color= a huge legend, repeated colors aggregate, filter the top N, or use facet_col
px.bar(..., barnorm="percent") TypeError: bar() got an unexpected keyword argument 'barnorm' fig.update_layout(barnorm="percent"), or px.histogram(..., histfunc="sum", barnorm="percent")
a numeric category column (a year, an id) in color= a continuous color bar instead of distinct colors df["year"].astype(str)
facet titles neighborhood=Lakeview long panel titles fig.for_each_annotation(...) as above
facets in data order panels in a random-looking order category_orders={"col": [...]}
trendline="ols" without statsmodels ModuleNotFoundError: No module named 'statsmodels' pip install statsmodels
a chart of a million rows huge HTML file, slow browser aggregate, sample, px.density_heatmap, or render_mode="webgl"
a self-contained HTML of 4.6 MB per chart big e-mails and repos include_plotlyjs="cdn" (needs internet to view)
hovertemplate and an animation frames lose the custom tooltip set the template on each frame’s traces too, or use hover_data formats

scipy.stats holds probability distributions, statistical tests and resampling tools. This page covers the distribution API, a test-selection table, effect sizes, confidence intervals, bootstrap and permutation_test. The examples use the checkout A/B test in data/ab_test.csv and the house sales in data/houses.csv. The blocks share one session:

import numpy as np
import pandas as pd
from scipy import stats
ab = pd.read_csv("data/ab_test.csv")
houses = pd.read_csv("data/houses.csv")
is_t = ab["group"] == "treatment"
t_time = ab.loc[is_t, "time_on_page_s"].to_numpy() # seconds on the page
c_time = ab.loc[~is_t, "time_on_page_s"].to_numpy()
buyers = ab[ab["converted"] == 1]
rev = buyers["revenue"].to_numpy() # order value of buyers
I want to… Use… Notes
a distribution with fixed parameters d = stats.norm(loc=m, scale=s) a “frozen” distribution
P(X ≤ x) d.cdf(x) discrete and continuous
P(X > x) d.sf(x) more precise than 1 - cdf in the tail
P(a < X ≤ b) d.cdf(b) - d.cdf(a)
P(X = k), discrete d.pmf(k) pdf is a density, not a probability
P(X ≥ k), discrete d.sf(k - 1) sf(k) is P(X > k)
the value at a quantile d.ppf(q) inverse of cdf
a central range with 95% probability d.interval(0.95)
repeatable random draws d.rvs(size=n, random_state=42) or a Generator
fit a distribution to data stats.lognorm.fit(x, floc=0) returns a tuple of parameters
check a fitted distribution stats.goodness_of_fit(dist, x, rng=rng) Monte Carlo p-value
compare a mean with a target stats.ttest_1samp(x, popmean=m)
compare two group means stats.ttest_ind(a, b, equal_var=False) Welch; the default is Student
compare paired measurements stats.ttest_rel(after, before) or stats.wilcoxon
compare two skewed groups stats.mannwhitneyu(a, b) ranks
compare 3+ group means stats.f_oneway(*groups, equal_var=False) Welch ANOVA
compare 3+ skewed groups stats.kruskal(*groups)
find which pairs differ stats.tukey_hsd(*groups) after ANOVA
test two categorical variables stats.chi2_contingency(table) table = pd.crosstab(a, b)
test counts against expected shares stats.chisquare(obs, f_exp=exp) sample ratio mismatch
test a small 2×2 table stats.fisher_exact(table) exact
test one proportion stats.binomtest(k, n, p=0.5) .proportion_ci()
a correlation with a p-value stats.pearsonr(x, y), stats.spearmanr(x, y) .confidence_interval() on Pearson
compare two whole distributions stats.ks_2samp(a, b)
check normality stats.probplot(x) (Q-Q), stats.shapiro(x) prefer the plot
check equal variances stats.levene(a, b)
a CI for a mean stats.t.interval(0.95, n - 1, loc=m, scale=stats.sem(x))
a CI for a difference of means stats.ttest_ind(...).confidence_interval()
a CI for any statistic stats.bootstrap((x,), np.median, rng=rng) BCa by default
a p-value for any statistic stats.permutation_test((a, b), stat, rng=rng) no distribution assumption
Cramér’s V stats.contingency.association(table)
an odds ratio with a CI stats.contingency.odds_ratio(table)
a relative risk with a CI stats.contingency.relative_risk(k1, n1, k2, n2)
adjust many p-values stats.false_discovery_control(p) Benjamini–Hochberg
standard error, IQR, z-scores stats.sem(x), stats.iqr(x), stats.zscore(x)
Method Gives Note
pdf(x) / pmf(k) density (continuous) / P(X = k) (discrete) logpdf, logpmf for tiny values
cdf(x) P(X ≤ x) logcdf
sf(x) P(X > x) = 1 − cdf survival function
ppf(q) the x with cdf(x) = q “percent point function” (quantile)
isf(q) the x with sf(x) = q upper critical values: stats.norm.isf(0.025)
interval(c) the central range with probability c
mean(), median(), var(), std() moments
stats(moments="mvsk") mean, variance, skew, excess kurtosis
expect(func) E[func(X)] numerical integral or sum
support() the range of possible values
rvs(size, random_state) random draws
fit(data) parameter estimates (MLE) only on the unfrozen class

Every method also works unfrozen, with the parameters as arguments: stats.norm.cdf(x, loc=m, scale=s). Freeze a distribution when you call it more than once.

Distribution scipy Parameters → meaning Use for
normal stats.norm(loc, scale) mean, sd measurement noise, sums
t stats.t(df, loc, scale) degrees of freedom small-sample means
chi-square stats.chi2(df) variance tests, contingency tables
F stats.f(dfn, dfd) ANOVA
uniform stats.uniform(loc=a, scale=b - a) width, not the upper end
exponential stats.expon(scale=1 / lam) scale = 1/rate waiting times
gamma stats.gamma(a, scale=theta) shape, scale positive skewed values
log-normal stats.lognorm(s=sigma, scale=np.exp(mu)) sd and exp(mean) of the log money, sizes
beta stats.beta(a, b) rates and proportions in 0–1
Weibull stats.weibull_min(c, scale) shape, scale lifetimes
binomial stats.binom(n, p) trials, success probability k successes in n trials
Poisson stats.poisson(mu) rate per interval counts of events
geometric stats.geom(p) trials up to the first success; starts at 1
negative binomial stats.nbinom(n, p) overdispersed counts; failures before n successes
hypergeometric stats.hypergeom(M, n, N) population, successes in it, draws draws without replacement
d = stats.norm(loc=87, scale=40) # frozen: time on page, roughly
print(round(d.cdf(120), 4), round(d.sf(120), 4)) # P(X <= 120), P(X > 120)
print(d.ppf([0.05, 0.5, 0.95]).round(1), np.round(d.interval(0.9), 1))
print(round(stats.norm.cdf(120, loc=87, scale=40), 4)) # the same, unfrozen
b = stats.binom(n=20, p=0.11) # 20 visitors, 11% convert
print(round(b.pmf(2), 4), round(b.cdf(2), 4), round(b.sf(4), 4)) # sf(4) = P(X >= 5)
print(round(stats.expon(scale=1 / 3).mean(), 4)) # rate 3 per hour -> 20 minutes
print(d.rvs(size=3, random_state=42).round(1))
print(round(stats.norm.isf(0.025), 3), round(stats.t(df=9).isf(0.025), 3)) # 2-sided 5%
Output
0.7953 0.2047
[ 21.2 87. 152.8] [ 21.2 152.8]
0.7953
0.2822 0.6198 0.061
0.3333
[106.9 81.5 112.9]
1.96 2.262
s, loc, scale = stats.lognorm.fit(rev, floc=0) # floc=0: the usual 2-parameter fit
print(round(s, 3), round(np.log(scale), 3)) # sigma and mu of log(revenue)
print(round(np.log(rev).std(), 3), round(np.log(rev).mean(), 3)) # the same by hand
fitted = stats.lognorm(s, loc=0, scale=scale)
print(round(fitted.sf(100), 4), round((rev > 100).mean(), 4)) # model tail vs data
gof = stats.goodness_of_fit(
stats.lognorm, rev, known_params={"loc": 0}, rng=np.random.default_rng(42)
)
print(round(gof.statistic, 3), round(gof.pvalue, 3)) # large p: no evidence of misfit
Output
0.643 3.541
0.643 3.541
0.0489 0.0468
0.201 0.885
Fitting tool Does Watch out
dist.fit(x) MLE of all parameters fix known ones: floc=0, fscale=1, f0=...
stats.fit(dist, x, bounds=...) MLE with bounds; returns FitResult without bounds for loc and scale, they stay at 0 and 1
stats.goodness_of_fit(dist, x) KS/AD test with the parameters re-fitted on each Monte Carlo sample slow on large data; pass rng
stats.kstest(x, "norm", args=(m, s)) KS test against known parameters with parameters fitted on x, the p-value is far too large
stats.probplot(x, dist=stats.lognorm(s)) Q-Q plot data and fit r plot=ax draws it

SciPy 1.15+ adds classes such as stats.Normal(mu=0, sigma=1) and stats.Uniform(a=0, b=1). Their methods have new names: icdf instead of ppf, ccdf instead of sf, sample(n, rng=rng) instead of rvs. stats.make_distribution(stats.gamma) turns a classic distribution into a class of this kind. The classic stats.norm API stays and is what most code uses.

Test When Function Assumptions
one-sample t one mean vs a target ttest_1samp(x, popmean=m) independent values; mean close to normal (CLT)
Welch t two independent means ttest_ind(a, b, equal_var=False) independent groups; no equal variances needed
Student t two means, equal variances ttest_ind(a, b) equal variances; rarely worth the risk
paired t before/after on the same units ttest_rel(after, before) differences close to normal
Mann–Whitney U two independent groups, skewed or ordinal mannwhitneyu(a, b) tests P(A > B) = 0.5, not medians
Brunner–Munzel like Mann–Whitney with unequal spreads brunnermunzel(a, b) no equal-spread assumption
Wilcoxon signed-rank paired or one-sample, skewed wilcoxon(after, before) symmetric differences
one-way ANOVA 3+ means f_oneway(*g) (equal_var=False: Welch) normal-ish groups
Kruskal–Wallis 3+ skewed groups kruskal(*g) independent groups; similar shapes only if you read it as a median test
Tukey HSD all pairs after ANOVA tukey_hsd(*g) equal variances; else equal_var=False
Friedman 3+ paired conditions friedmanchisquare(a, b, c) blocks of related values
chi-square independence two categorical variables chi2_contingency(table) expected counts ≥ 5
chi-square goodness of fit counts vs expected shares chisquare(obs, f_exp=exp) sums of obs and f_exp match
Fisher exact small 2×2 table fisher_exact(table) fixed margins
Barnard / Boschloo small 2×2 table, more power barnard_exact(t), boschloo_exact(t) slow for large counts
binomial one proportion vs p binomtest(k, n, p) independent trials
Pearson linear association pearsonr(x, y) linear; outliers distort it
Spearman / Kendall monotonic association spearmanr(x, y), kendalltau(x, y) ranks
KS two-sample any difference in distribution ks_2samp(a, b) continuous data
Shapiro–Wilk normality shapiro(x) too sensitive at large n
Levene equal variances levene(a, b) robust to non-normality
permutation any statistic, few assumptions permutation_test(data, stat) exchangeable under H0
Member Gives
res.statistic, res.pvalue on every test result; also unpacks: t, p = res
res.df degrees of freedom (t-tests; res.dof for chi2_contingency)
res.confidence_interval(0.95) t-tests, pearsonr, binomtest (proportion_ci), odds_ratio
res.expected_freq expected counts of chi2_contingency
alternative="less" / "greater" one-sided H1 about the first argument, decided in advance
nan_policy="omit" drop NaN instead of returning nan
axis=0 test every column of a 2-D array at once
print(f"Welch t: p = {stats.ttest_ind(t_time, c_time, equal_var=False).pvalue:.1e}")
res = stats.ttest_ind(t_time, c_time, equal_var=False)
print(np.round(res.confidence_interval(), 2), round(res.df, 1)) # CI of t - c
t_rev = buyers.loc[buyers["group"] == "treatment", "revenue"]
c_rev = buyers.loc[buyers["group"] == "control", "revenue"]
print(f"Mann-Whitney p = {stats.mannwhitneyu(t_rev, c_rev).pvalue:.3f}")
table = pd.crosstab(ab["group"], ab["converted"])
chi = stats.chi2_contingency(table) # Yates' correction on 2x2 by default
print(f"chi2 = {chi.statistic:.2f}, dof = {chi.dof}, p = {chi.pvalue:.4f}")
srm = stats.chisquare(ab["group"].value_counts()) # expected: a 50/50 split
print(f"SRM p = {srm.pvalue:.3f}")
by_device = [g.to_numpy() for _, g in ab.groupby("device")["time_on_page_s"]]
print(f"Welch ANOVA p = {stats.f_oneway(*by_device, equal_var=False).pvalue:.1e}")
print(f"Kruskal p = {stats.kruskal(*by_device).pvalue:.1e}")
Output
Welch t: p = 2.5e-17
[ 6.95 11.12] 9989.3
Mann-Whitney p = 0.282
chi2 = 6.02, dof = 1, p = 0.0141
SRM p = 0.968
Welch ANOVA p = 3.5e-40
Kruskal p = 4.9e-51
before = np.array([12.1, 9.8, 11.4, 13.0, 10.2, 12.7, 9.5, 11.9]) # same 8 users
after = np.array([11.0, 9.9, 10.1, 12.2, 9.0, 12.5, 8.7, 11.1])
print(round(stats.ttest_rel(after, before).pvalue, 4)) # paired: test the differences
print(round(stats.wilcoxon(after, before).pvalue, 4)) # rank version
print(round(stats.ttest_ind(after, before).pvalue, 4)) # wrong: ignores the pairing
x, y = np.log(houses["sqft"]), np.log(houses["price"])
r = stats.pearsonr(x, y)
print(round(r.statistic, 3), np.round(r.confidence_interval(), 3))
print(round(stats.spearmanr(houses["sqft"], houses["price"]).statistic, 3))
Output
0.003
0.0156
0.2823
0.703 [0.684 0.721]
0.679
p = np.array([0.001, 0.008, 0.039, 0.041, 0.042, 0.060, 0.074, 0.205])
print(np.round(stats.false_discovery_control(p), 3)) # BH-adjusted p-values
print((stats.false_discovery_control(p) <= 0.05).sum(), (p * len(p) <= 0.05).sum())
Output
[0.008 0.032 0.067 0.067 0.067 0.08 0.085 0.205]
2 1

The second line counts the discoveries at 5%: Benjamini–Hochberg finds 2, Bonferroni (p × m) finds 1.

A p-value says whether an effect is distinguishable from noise. An effect size says how large it is. Report both.

Effect size Formula or code Rough scale
difference of means a.mean() - b.mean() with its CI in the units of the data
Cohen’s d (xˉ1−xˉ2)/sp(\bar{x}_1 - \bar{x}_2) / s_p 0.2 small, 0.5 medium, 0.8 large
Hedges’ g d×(1−3/(4(n1+n2)−9))d \times (1 - 3 / (4(n_1 + n_2) - 9)) d corrected for small samples
difference of rates p^1−p^2\hat{p}_1 - \hat{p}_2 percentage points
relative lift / risk p^1/p^2\hat{p}_1 / \hat{p}_2 stats.contingency.relative_risk
odds ratio p1/(1−p1)p2/(1−p2)\frac{p_1/(1-p_1)}{p_2/(1-p_2)} stats.contingency.odds_ratio; 1 = no effect
rank-biserial r 2U/(n1n2)−12U / (n_1 n_2) - 1 −1 to 1; 0 = no tendency
Pearson r, Spearman ρ pearsonr, spearmanr 0.1 small, 0.3 medium, 0.5 large
Cramér’s V stats.contingency.association(table) 0.1 weak, 0.3 moderate (2 columns)
η² (ANOVA) between-group SS / total SS share of variance explained
def cohens_d(a: np.ndarray, b: np.ndarray) -> float:
"""Standardized mean difference with the pooled standard deviation."""
n1, n2 = len(a), len(b)
pooled = ((n1 - 1) * a.var(ddof=1) + (n2 - 1) * b.var(ddof=1)) / (n1 + n2 - 2)
return (a.mean() - b.mean()) / np.sqrt(pooled)
print(round(cohens_d(t_time, c_time), 3)) # tiny p, effect below "small" (0.2)
u = stats.mannwhitneyu(t_rev, c_rev).statistic
print(round(2 * u / (len(t_rev) * len(c_rev)) - 1, 3)) # rank-biserial r
rr = stats.contingency.relative_risk(583, 4998, 506, 5002) # k_t, n_t, k_c, n_c
print(round(rr.relative_risk, 3), np.round(rr.confidence_interval(), 3))
odds = stats.contingency.odds_ratio([[583, 4415], [506, 4496]], kind="sample")
print(round(odds.statistic, 3), np.round(odds.confidence_interval(), 3))
v = stats.contingency.association(pd.crosstab(ab["device"], ab["converted"]))
print(round(v, 3)) # Cramer's V: a weak association
Output
0.17
-0.038
1.153 [1.03 1.29]
1.173 [1.034 1.331]
0.06
Interval for Code
a mean stats.t.interval(0.95, len(x) - 1, loc=x.mean(), scale=stats.sem(x))
a difference of means stats.ttest_ind(a, b, equal_var=False).confidence_interval()
a paired difference stats.ttest_rel(after, before).confidence_interval()
a proportion stats.binomtest(k, n).proportion_ci(method="wilson")
a correlation stats.pearsonr(x, y).confidence_interval()
an odds ratio / relative risk .confidence_interval() on the contingency results
any statistic stats.bootstrap(...) (next section)
m, se = t_time.mean(), stats.sem(t_time)
print(np.round(stats.t.interval(0.95, len(t_time) - 1, loc=m, scale=se), 2))
ci = stats.binomtest(583, 4998).proportion_ci(confidence_level=0.95, method="wilson")
print(round(ci.low, 4), round(ci.high, 4)) # treatment conversion rate
Output
[90.26 93.26]
0.108 0.1258

stats.bootstrap resamples the data with replacement, recomputes the statistic and builds a CI from the spread of the results. Use it for medians, ratios, trimmed means and other statistics with no simple formula.

Argument Meaning
data a tuple of samples: (x,) for one, (a, b) for two (resampled separately)
statistic a function of the samples; with an axis argument it runs vectorized (fast)
n_resamples=9999 the number of resamples
method="BCa" also "percentile", "basic"; BCa corrects for bias and skew
paired=True resample pairs together (data=(x, y) of equal length)
confidence_level=0.95 the CI level
rng=np.random.default_rng(42) repeatable results
Result Gives
res.confidence_interval .low, .high
res.standard_error the bootstrap standard error
res.bootstrap_distribution every resampled statistic (for a histogram)
rng = np.random.default_rng(42)
boot = stats.bootstrap((rev,), np.median, rng=rng) # one sample: note the comma
print(np.round(boot.confidence_interval, 2), round(boot.standard_error, 3))
def diff_medians(a: np.ndarray, b: np.ndarray, axis: int) -> np.ndarray:
return np.median(a, axis=axis) - np.median(b, axis=axis)
two = stats.bootstrap((t_rev.to_numpy(), c_rev.to_numpy()), diff_medians, rng=rng)
print(np.round(two.confidence_interval, 2)) # includes 0: no clear change
print(two.bootstrap_distribution.shape)
Output
[33.21 36.7 ] 0.946
[-5.36 1.9 ]
(9999,)

stats.permutation_test builds the null distribution by shuffling. Under H0 the labels do not matter, so the observed statistic should look like the shuffled ones. The p-value is the share of shuffled statistics at least as extreme as the observed one.

permutation_type Shuffles Use for data
"independent" (default) values between the groups two or more independent groups (a, b)
"samples" within each pair (signs of the difference) paired data (after, before)
"pairings" which x goes with which y correlation (x, y)
def diff_means(a: np.ndarray, b: np.ndarray, axis: int) -> np.ndarray:
return a.mean(axis=axis) - b.mean(axis=axis)
res = stats.permutation_test(
(t_time, c_time), diff_means, n_resamples=2_000, vectorized=True, rng=rng
)
print(round(res.statistic, 2), round(res.pvalue, 4)) # no shuffle came close
paired = stats.permutation_test(
(after, before), diff_means, permutation_type="samples", rng=rng
)
print(round(paired.statistic, 3), round(paired.pvalue, 4)) # 2**8 = 256: exact
def pearson_r(x: np.ndarray, y: np.ndarray) -> float:
return stats.pearsonr(x, y).statistic
corr = stats.permutation_test(
(before, after), pearson_r, permutation_type="pairings", rng=rng
)
print(round(corr.statistic, 3), round(corr.pvalue, 4))
Output
9.03 0.001
-0.762 0.0156
0.937 0.0016

The first p-value is the smallest possible one with 2,000 shuffles: 2/20012 / 2001 for a two-sided test. Raise n_resamples for more resolution. With few possible arrangements, as for 8 pairs, the test enumerates them all and the p-value is exact.

The tests also accept a resampling method: stats.ttest_ind(a, b, method=stats.PermutationMethod(rng=rng)) and stats.pearsonr(x, y, method=stats.PermutationMethod()) keep their usual statistic but compute the p-value by permutation.

Trap Symptom Fix
ttest_ind(a, b) with unequal variances p-value too small or too large equal_var=False (Welch) by default
sf(k) for “at least k” on a discrete distribution off by one value sf(k - 1)
stats.expon(lam) the mean is wrong: the first argument is loc stats.expon(scale=1 / lam)
stats.uniform(a, b) the range is a to a + b stats.uniform(loc=a, scale=b - a)
stats.lognorm(mu, sigma) nonsense values stats.lognorm(s=sigma, scale=np.exp(mu))
stats.geom.pmf(0, p) is 0 counts start at 1 use k - 1 failures or stats.nbinom(1, p)
dist(...).fit(x) AttributeError: a frozen distribution has no fit stats.norm.fit(x) on the class
stats.fit(stats.norm, x) loc=0, scale=1, whatever the data pass bounds for loc and scale, or use stats.norm.fit
lognorm.fit(x) without floc=0 a 3-parameter fit with a strange loc floc=0
kstest with parameters fitted on the same data p-values far too large stats.goodness_of_fit
stats.anderson(x) FutureWarning in SciPy 1.17+ pass method="interpolate" or a MonteCarloMethod
chisquare(obs, f_exp=shares) ValueError: the sums of observed and expected frequencies differ expected counts: f_exp=np.array(shares) * obs.sum()
chi2_contingency on a 2×2 table p differs from a z-test of two rates Yates’ correction; correction=False matches the z-test
odds_ratio(table) differs a little from the hand formula the default is the conditional MLE; kind="sample" for the plain ratio
stats.bootstrap(x, ...) AxisError: axis is out of bounds for array of dimension 0 pass a tuple: (x,)
a non-vectorized statistic bootstrap or permutation_test is slow accept axis and use .mean(axis=axis)
no rng different results on every run rng=np.random.default_rng(42)
permutation p-value of 0.0005 or 0.001 it is the floor, not the truth the floor is 1 / (n_resamples + 1) (two-sided: twice that); raise n_resamples
mannwhitneyu read as a test of medians wrong conclusion when shapes differ it tests whether one group tends to give larger values
alternative="greater" the direction is reversed it refers to the first argument minus the second
shapiro on thousands of rows rejects harmless departures read a Q-Q plot (stats.probplot)
pearsonr on trending or skewed data strong but spurious r spearmanr, logs, or differences
NaN in the input the result is nan nan_policy="omit" or dropna() first
many tests at α = 0.05 false discoveries stats.false_discovery_control(p)

statsmodels fits statistical models with full inference: standard errors, p-values and confidence intervals. This page covers the formula API, reading results, robust standard errors, proportions tests, power analysis and the first time-series tools. The examples use data/houses.csv, the A/B test in data/ab_test.csv and the daily visits in data/web_traffic.csv. The blocks share one session:

import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
houses = pd.read_csv("data/houses.csv")
ab = pd.read_csv("data/ab_test.csv")
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")
I want to… Use… Notes
a linear regression with inference smf.ols("y ~ x1 + x2", data=df).fit()
the same with arrays sm.OLS(y, sm.add_constant(X)).fit() no intercept unless you add it
a logistic regression smf.logit("y ~ x", data=df).fit(disp=0) y is 0/1
a count model smf.poisson(...) or smf.glm(..., family=sm.families.Poisson())
any GLM smf.glm(f, data=df, family=sm.families.Binomial()) Gamma, NegativeBinomial, Tweedie
weighted least squares smf.wls(f, data=df, weights=w)
a median regression smf.quantreg(f, data=df).fit(q=0.5) robust to outliers
random effects per group smf.mixedlm(f, data=df, groups=df["g"])
a categorical predictor C(cat) in the formula dummies; first level is the reference
choose the reference level C(cat, Treatment(reference="B"))
an interaction x1 * x2 or x1:x2 * adds the main effects too
a transform in the formula np.log(y) ~ np.log(x), I(x ** 2)
coefficients res.params a Series
standard errors, p-values res.bse, res.pvalues
95% CIs of the coefficients res.conf_int(alpha=0.05) columns 0 and 1
R² res.rsquared, res.rsquared_adj OLS; prsquared for logit
AIC, BIC res.aic, res.bic lower is better
rows used res.nobs rows with NaN are dropped
check for unequal error variance het_breuschpagan(res.resid, res.model.exog) p < 0.05: use HC3
check for collinearity variance_inflation_factor(res.model.exog, i) above 5–10 is a problem
find influential rows res.get_influence().cooks_distance[0] compare with 4 / n
robust standard errors .fit(cov_type="HC3") same coefficients
clustered standard errors .fit(cov_type="cluster", cov_kwds={"groups": g}) many clusters needed
autocorrelation-robust SE .fit(cov_type="HAC", cov_kwds={"maxlags": 7}) time series
predictions with intervals res.get_prediction(new).summary_frame(alpha=0.05) mean CI and prediction interval
odds ratios np.exp(logit_res.params)
marginal effects logit_res.get_margeff().summary_frame() in probability units
test “coefficient = value” res.t_test("x = 0.5") f_test for several
an ANOVA table sm.stats.anova_lm(res, typ=2)
compare two conversion rates proportions_ztest(counts, nobs) statsmodels.stats.proportion
a CI for a difference of rates confint_proportions_2indep(k1, n1, k2, n2) Newcombe, Wilson
a CI for one rate proportion_confint(k, n, method="wilson")
a sample size for an A/B test NormalIndPower().solve_power(effect_size=h, power=0.8) h = proportion_effectsize(p1, p2)
a sample size for a t-test TTestIndPower().solve_power(effect_size=d, power=0.8) per group
adjust many p-values multipletests(p, method="fdr_bh") "holm", "bonferroni"
test for a unit root adfuller(y, result_object=True) H0: not stationary
decompose a series STL(y, period=7).fit() trend, seasonal, remainder
fit a (seasonal) ARIMA SARIMAX(y, order=..., seasonal_order=...).fit(disp=False)

statsmodels.formula.api (smf) builds the design matrix from a formula string and a DataFrame. It adds an intercept, makes dummy variables and keeps the column names.

Formula Meaning
y ~ x intercept + slope
y ~ x1 + x2 two predictors
y ~ C(cat) one dummy per level except the first (the reference)
y ~ C(cat, Treatment(reference="B")) B is the reference level
y ~ C(num) treat a numeric column (such as a 1–5 rating) as categories
y ~ x1 * x2 x1 + x2 + x1:x2
y ~ x1:x2 the interaction only
y ~ C(cat) * x one slope of x per category
np.log(y) ~ np.log(x) NumPy functions work inside the formula
y ~ I(x ** 2) arithmetic needs I(...); a bare x ** 2 means something else
y ~ x - 1 or y ~ 0 + x no intercept
y ~ Q("my col") a column name that is not a Python name
y ~ scale(x) / center(x) standardize or center inside the formula
Function Model y
smf.ols linear regression numeric
smf.wls weighted linear regression numeric
smf.logit, smf.probit binary outcome 0/1
smf.mnlogit several unordered classes integer codes
smf.poisson, smf.negativebinomial counts integers ≥ 0
smf.glm any GLM: pass family=sm.families.Gaussian(), Binomial(), Poisson(), Gamma()… depends on the family
smf.quantreg a quantile of y; .fit(q=0.9) numeric
smf.mixedlm random intercepts or slopes per group numeric
formula = "np.log(price) ~ np.log(sqft) + has_pool + C(neighborhood)"
ols = smf.ols(formula, data=houses).fit()
coefs = pd.DataFrame({"coef": ols.params, "se": ols.bse, "p": ols.pvalues})
coefs[["low", "high"]] = ols.conf_int(alpha=0.05) # 95% CI per coefficient
print(coefs.loc[["np.log(sqft)", "has_pool", "C(neighborhood)[T.Lakeview]"]].round(4))
print(round(ols.rsquared, 3), round(ols.rsquared_adj, 3), int(ols.nobs), ols.df_model)
print(f"pool: {100 * (np.exp(ols.params['has_pool']) - 1):+.1f}% price") # log outcome
Output
coef se p low high
np.log(sqft) 0.7556 0.0124 0.0 0.7312 0.7800
has_pool 0.0972 0.0138 0.0 0.0700 0.1243
C(neighborhood)[T.Lakeview] 0.8952 0.0176 0.0 0.8607 0.9297
0.819 0.818 3000 9.0
pool: +10.2% price
Result member Gives
params, bse, tvalues, pvalues coefficients, standard errors, t statistics, p-values (Series)
conf_int(alpha=0.05) a DataFrame with columns 0 and 1
rsquared, rsquared_adj share of variance explained (OLS)
fvalue, f_pvalue the F-test of “all slopes are 0”
aic, bic, llf information criteria, log-likelihood
nobs, df_model, df_resid rows used, number of slopes, residual degrees of freedom
resid, fittedvalues residuals and fitted values of the training rows
predict(new_df) point predictions; the formula is applied to new_df
get_prediction(new_df) predictions with standard errors and intervals
model.exog_names the design-matrix column names
t_test("x = 0"), f_test("x1 = x2 = 0") tests of linear restrictions
summary() the full report as text

summary() prints the full report. Its header contains the date and time of the call, so it changes on every run:

print(ols.summary()) # header, coefficient table and residual diagnostics
print(ols.summary().tables[1]) # only the coefficient table

In a model of np.log(y), a coefficient β\beta of a 0/1 predictor changes yy by 100(eβ−1)%100(e^{\beta} - 1)\%. The coefficient of np.log(x) is an elasticity: +1% of x gives about β\beta% of y.

Reference levels, interactions and missing rows

Section titled “Reference levels, interactions and missing rows”
ref = "C(neighborhood, Treatment(reference='Downtown'))"
m_ref = smf.ols(f"np.log(price) ~ np.log(sqft) + {ref}", data=houses).fit()
levels = [name.split("[T.")[1][:-1] for name in m_ref.model.exog_names[1:3]]
print(levels) # these dummies are now relative to Downtown
inter = smf.ols("np.log(price) ~ np.log(sqft) * has_pool", data=houses).fit()
print(inter.params.round(3).to_dict()) # has_pool: the effect at log(sqft) = 0
lot = smf.ols("np.log(price) ~ lot_sqft", data=houses).fit()
print(houses["lot_sqft"].isna().sum(), int(lot.nobs)) # 90 NaN rows dropped
Output
['Cedar Park', 'Lakeview']
{'Intercept': 6.281, 'np.log(sqft)': 0.886, 'has_pool': -3.193, 'np.log(sqft):has_pool': 0.455}
90 2910

The last line shows the silent row drop: 90 rows with a missing lot_sqft leave 2,910 rows in the model.

new = pd.DataFrame(
{"sqft": [1500, 2500], "has_pool": [0, 1], "neighborhood": ["Old Town", "Lakeview"]}
)
frame = ols.get_prediction(new).summary_frame(alpha=0.05) # on the log scale
print(frame.columns.tolist())
print(np.exp(frame[["mean", "obs_ci_lower", "obs_ci_upper"]]).round(-3))
Output
['mean', 'mean_se', 'mean_ci_lower', 'mean_ci_upper', 'obs_ci_lower', 'obs_ci_upper']
mean obs_ci_lower obs_ci_upper
0 346000.0 223000.0 536000.0
1 952000.0 613000.0 1477000.0

mean_ci_* is the CI of the average price of such houses. obs_ci_* is the prediction interval for one house: much wider. np.exp of a log-scale prediction gives the median, not the mean.

Check the model before you trust its p-values. Each check below tests one assumption of OLS.

Check Function A problem looks like Then
linearity, unequal variance plot res.fittedvalues vs res.resid a curve, or a fan shape transform y or x; cov_type="HC3"
unequal variance, as a test het_breuschpagan(res.resid, res.model.exog) p < 0.05 cov_type="HC3"
normal residuals sm.qqplot(res.resid, line="45", fit=True) points bend away from the line matters for small samples and prediction intervals
collinearity variance_inflation_factor(res.model.exog, i) VIF above 5–10 drop or combine predictors
influential rows res.get_influence().cooks_distance[0] a few values far above 4 / n inspect those rows; refit without them to compare
autocorrelated errors durbin_watson(res.resid) far from 2 (below 1.5 or above 2.5) cov_type="HAC", or a time-series model
from statsmodels.stats.diagnostic import het_breuschpagan
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.stats.stattools import durbin_watson
bp_p = het_breuschpagan(ols.resid, ols.model.exog)[1]
print(f"Breusch-Pagan p = {bp_p:.4f}") # small: the spread is not constant
X, names = ols.model.exog, ols.model.exog_names
vif = {n: round(float(variance_inflation_factor(X, i)), 2)
for i, n in enumerate(names) if n in ("np.log(sqft)", "has_pool")}
print(vif) # near 1: no collinearity problem
cooks = ols.get_influence().cooks_distance[0]
print(round(cooks.max(), 4), houses.loc[cooks.argmax(), "house_id"],
int((cooks > 4 / ols.nobs).sum())) # largest, its row, count above 4/n
print(round(durbin_watson(ols.resid), 3)) # near 2: no autocorrelation
Output
Breusch-Pagan p = 0.0000
{'np.log(sqft)': 1.3, 'has_pool': 1.11}
0.0199 H0542 158
1.989
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1, 2, figsize=(9, 3.5), layout="constrained")
axs[0].scatter(ols.fittedvalues, ols.resid, s=5, alpha=0.4) # residuals vs fitted
axs[0].axhline(0, color="gray")
sm.qqplot(ols.resid, line="45", fit=True, ax=axs[1]) # residuals vs a normal
plt.show()

The small Breusch–Pagan p-value is the reason to use the HC3 standard errors below.

cov_type Use when Extra argument
"nonrobust" (default) constant error variance, independent errors
"HC3" the residual spread changes (a fan shape)
"HC0", "HC1" as HC3; HC1 matches Stata’s robust
"cluster" errors correlate within groups (users, stores, schools) cov_kwds={"groups": df["g"]}
"HAC" autocorrelated errors in a time series cov_kwds={"maxlags": 7}
robust = smf.ols(formula, data=houses).fit(cov_type="HC3")
compare = pd.DataFrame({"classic": ols.bse, "HC3": robust.bse})
print(compare.loc[["np.log(sqft)", "has_pool"]].round(4))
print(np.allclose(ols.params, robust.params)) # only the standard errors change
Output
classic HC3
np.log(sqft) 0.0124 0.0148
has_pool 0.0138 0.0152
True

Clustered standard errors need many clusters (dozens or more). With the 8 neighborhoods of houses.csv, they would be unreliable.

logit = smf.logit("converted ~ C(group) + C(device)", data=ab).fit(disp=0) # quiet
print(logit.params.round(4))
print(np.exp(logit.params).round(3)["C(group)[T.treatment]"]) # odds ratio
print(round(logit.prsquared, 4), f"{logit.llr_pvalue:.1e}") # pseudo R², LR test
effects = logit.get_margeff().summary_frame() # average marginal effects
print(effects["dy/dx"].round(4))
new_users = pd.DataFrame({"group": ["control", "treatment"], "device": "desktop"})
print(logit.predict(new_users).round(4).tolist()) # probabilities
Output
Intercept -1.9621
C(group)[T.treatment] 0.1597
C(device)[T.mobile] -0.4035
C(device)[T.tablet] -0.1155
dtype: float64
1.173
0.0061 4.2e-09
C(group)[T.treatment] 0.0154
C(device)[T.mobile] -0.0390
C(device)[T.tablet] -0.0112
Name: dy/dx, dtype: float64
[0.1232, 0.1416]

The treatment raises the odds of a purchase by about 17%. The marginal effect says the same in probability units: about +1.5 percentage points. smf.glm("converted ~ C(group) + C(device)", data=ab, family=sm.families.Binomial()) fits the same model as a GLM.

two_way = smf.ols("np.log(price) ~ C(neighborhood) + C(condition)", data=houses).fit()
print(sm.stats.anova_lm(two_way, typ=2).round(3)) # Type II sums of squares
Output
sum_sq df F PR(>F)
C(neighborhood) 468.911 7.0 661.803 0.0
C(condition) 39.635 4.0 97.894 0.0
Residual 302.444 2988.0 NaN NaN
typ Tests each term Use for
1 after the terms before it (the order matters) nested, ordered models
2 after all other main effects models without interactions (the usual choice)
3 after all other terms models with interactions; needs Sum contrasts

All in statsmodels.stats.proportion.

Function Gives
proportions_ztest(count, nobs) z and p for two (or one) rates; pooled variance
proportions_chisquare(count, nobs) chi-square test of several rates
test_proportions_2indep(k1, n1, k2, n2) a test of two rates with a choice of method and of compare="diff", "ratio", "odds-ratio"
confint_proportions_2indep(k1, n1, k2, n2, method="newcomb") a CI for p1 - p2; compare="ratio" for the lift
proportion_confint(k, n, method="wilson") a CI for one rate; also "beta" (exact), "agresti_coull"
proportion_effectsize(p1, p2) Cohen’s h, the input of the power functions
binom_test(k, n, prop=p) an exact test of one rate
from statsmodels.stats.proportion import (
confint_proportions_2indep,
proportion_confint,
proportions_ztest,
)
counts = ab.groupby("group")["converted"].agg(["sum", "count"])
k = counts.loc[["treatment", "control"], "sum"].to_numpy()
n = counts.loc[["treatment", "control"], "count"].to_numpy()
z, p = proportions_ztest(k, n) # two-sided by default
print(f"rates {k[0] / n[0]:.4f} vs {k[1] / n[1]:.4f}, z = {z:.3f}, p = {p:.4f}")
lo, hi = confint_proportions_2indep(k[0], n[0], k[1], n[1], method="newcomb")
print(f"difference: {100 * lo:.2f} to {100 * hi:.2f} pp")
lo, hi = confint_proportions_2indep(k[0], n[0], k[1], n[1], compare="ratio")
print(f"ratio: {lo:.3f} to {hi:.3f}") # relative lift +3% to +29%
print(np.round(proportion_confint(k[0], n[0], method="wilson"), 4))
Output
rates 0.1166 vs 0.1012, z = 2.486, p = 0.0129
difference: 0.33 to 2.77 pp
ratio: 1.030 to 1.290
[0.108 0.1258]

Plan the sample size before a study. Fix three of effect size, α, power and n; solve_power finds the one you leave out (pass it as None or leave it out).

Class Test Effect size
NormalIndPower() two proportions (z-test) Cohen’s h: proportion_effectsize(p1, p2)
TTestIndPower() two independent means Cohen’s d
TTestPower() paired or one-sample mean d of the differences
FTestAnovaPower() one-way ANOVA; returns the total n Cohen’s f; pass k_groups
GofChisquarePower() chi-square goodness of fit Cohen’s w
from statsmodels.stats.power import NormalIndPower, TTestIndPower, TTestPower
from statsmodels.stats.proportion import proportion_effectsize
h = proportion_effectsize(0.12, 0.10) # detect 10% -> 12%
print(round(h, 4), int(np.ceil(NormalIndPower().solve_power(h, alpha=0.05, power=0.8))))
print(round(NormalIndPower().power(h, nobs1=5_000, alpha=0.05), 3)) # power at 5,000
mde = NormalIndPower().solve_power(nobs1=5_000, alpha=0.05, power=0.8) # smallest h
print(round(mde, 4))
d_power = {"effect_size": 0.3, "alpha": 0.05, "power": 0.8} # Cohen's d = 0.3
print(int(np.ceil(TTestIndPower().solve_power(**d_power)))) # per group
print(int(np.ceil(TTestPower().solve_power(**d_power)))) # paired: number of pairs
Output
0.064 3835
0.892
0.056
176
90

The ratio=n2/n1 argument plans unequal groups; nobs1 is the size of the first group.

from statsmodels.stats.multitest import multipletests
p = np.array([0.001, 0.008, 0.039, 0.041, 0.042, 0.060, 0.074, 0.205])
for method in ["bonferroni", "holm", "fdr_bh"]:
reject, p_adj, _, _ = multipletests(p, alpha=0.05, method=method)
print(f"{method:<10}", reject.sum(), p_adj.round(3)[:3])
Output
bonferroni 1 [0.008 0.064 0.312]
holm 1 [0.008 0.056 0.234]
fdr_bh 2 [0.008 0.032 0.067]

Bonferroni and Holm control the chance of any false positive (family-wise error rate). fdr_bh controls the share of false positives among the discoveries and keeps more power.

The time-series module covers these in depth.

Task Function Note
unit-root test adfuller(y, result_object=True) H0: a unit root (not stationary)
stationarity test kpss(y, result_object=True) H0: stationary; the reverse of ADF
autocorrelation acf(y, nlags=14), pacf(y, nlags=14) statsmodels.tsa.stattools
ACF and PACF plots plot_acf(y, lags=28, ax=ax), plot_pacf statsmodels.graphics.tsaplots
decomposition STL(y, period=7, robust=True).fit() .trend, .seasonal, .resid
classical decomposition seasonal_decompose(y, period=7) NaN at both ends
(seasonal) ARIMA SARIMAX(y, order=(p, d, q), seasonal_order=(P, D, Q, s)) statsmodels.tsa.statespace.sarimax
exponential smoothing ExponentialSmoothing(y, trend="add", seasonal="add", seasonal_periods=7) statsmodels.tsa.holtwinters
forecast with intervals res.get_forecast(steps=28) .predicted_mean, .conf_int()
autocorrelation of residuals acorr_ljungbox(res.resid, lags=[7, 14]) statsmodels.stats.diagnostic
from statsmodels.tsa.stattools import adfuller
visits = traffic["visits"].interpolate() # ADF needs a series without gaps
for name, series in [("level", visits), ("first difference", visits.diff().dropna())]:
res = adfuller(series, result_object=True)
print(f"{name:<17} stat = {res.statistic:7.2f}, p = {res.pvalue:.2g}", end=", ")
print(f"lags = {res.lags}") # lagged differences chosen by AIC
Output
level stat = -2.51, p = 0.11, lags = 21
first difference stat = -10.89, p = 1.2e-19, lags = 20

The level shows no evidence of stationarity (p > 0.05); the ADF test rejects a unit root for the first difference (p < 0.05). That suggests d = 1 in an ARIMA model.

from statsmodels.tsa.statespace.sarimax import SARIMAX
model = SARIMAX(np.log(y_train), order=(1, 1, 1), seasonal_order=(0, 1, 1, 7))
result = model.fit(disp=False, maxiter=200) # disp=False: no optimizer printout
print(result.mle_retvals["converged"], round(result.aic, 1)) # check convergence
forecast = result.get_forecast(steps=28)
point = np.exp(forecast.predicted_mean) # back from the log scale
band = np.exp(forecast.conf_int(alpha=0.05))
Trap Symptom Fix
sm.OLS(y, X) without a constant the line goes through 0; R² is uncentered and too high sm.add_constant(X) or use smf.ols
missing values nobs is lower than len(df), without a message check res.nobs; impute or drop on purpose
y ~ x ** 2 not a square term I(x ** 2)
a numeric code such as a 1–5 rating one slope instead of one effect per level C(rating)
comparing coefficients across scales a big coefficient on a small unit standardize with scale(x) or compare effects in real units
the default nonrobust SE with a fan-shaped residual plot standard errors too small cov_type="HC3"
repeated rows per user or store standard errors far too small cov_type="cluster" with the group, or mixedlm
logit(...).fit() an optimizer message on stdout fit(disp=0)
PerfectSeparationWarning, ConvergenceWarning, huge logit coefficients a predictor splits the classes perfectly drop or merge the predictor, or regularize (fit_regularized)
logit coefficients read as probabilities wrong effect sizes np.exp(params) for odds ratios; get_margeff() for probabilities
summary() in a report or a test output changes with the date summary().tables[1] or build a table from params, bse, pvalues
get_margeff().summary_frame() columns the upper CI column is named Cont. Int. Hi. select by position or rename
np.exp of a log-scale forecast treated as the mean it is the median; the mean is a little higher
anova_lm(typ=1) results depend on the order of the terms typ=2 (or typ=3 with Sum contrasts)
FTestAnovaPower().solve_power n looks too large it returns the total over all groups
solve_power(effect_size=0.3, power=0.8) ValueError: need exactly one keyword that is None alpha has no default: pass alpha=0.05
NormalIndPower with two rates an error or a wrong n pass Cohen’s h from proportion_effectsize, not the difference
proportions_ztest(k, n) order the sign of z flips z > 0 when the first rate is the larger one; keep k and n in the same order
adfuller(y) or kpss(y) without result_object=True a FutureWarning in statsmodels 0.15 pass result_object=True; read .statistic, .pvalue
kpss p-value at 0.01 or 0.1 InterpolationWarning: the statistic is outside the table report “p < 0.01” or “p > 0.1” from the critical values
a large ADF p-value read as “the series has a unit root” it only means no evidence of stationarity
SARIMAX(...).fit() ConvergenceWarning a simpler model, the log of the series, maxiter=200; check mle_retvals["converged"]
a time series with NaN adfuller raises MissingDataError fill gaps first (interpolate, asfreq)
a formula with a column such as floor area SyntaxError Q("floor area"), or rename the column

SQL (Structured Query Language) asks a database for rows. This page covers the SQL you need for analysis, the two engines of the course and their Python APIs: SQLite (in the standard library, one file per database) and DuckDB (an analytics engine that also queries CSV, Parquet and DataFrames). Examples use the course database data/shop.db (tables stores, products, customers, orders) and data/sales.csv. SQL blocks are for reading; the Python blocks run them.

I want to… Use… Example
open a SQLite file read-only URI mode sqlite3.connect("file:data/shop.db?mode=ro", uri=True)
a throwaway database in memory sqlite3.connect(":memory:"), duckdb.connect()
run a query, get tuples execute + fetchall con.execute(sql, params).fetchall()
get one row / one value fetchone() (n,) = con.execute("SELECT COUNT(*) FROM orders").fetchone()
rows as dicts con.row_factory = sqlite3.Row row["city"], dict(row)
column names cur.description [c[0] for c in cur.description]
pass a value safely ? placeholder + tuple con.execute("SELECT * FROM stores WHERE region = ?", ("West",))
pass named values :name (sqlite3), $name (DuckDB) params={"start": "2024-01-01"}
insert many rows executemany con.executemany("INSERT INTO t VALUES (?, ?)", rows)
commit or roll back as one unit with con: with con: con.executemany(...)
query a CSV or Parquet file DuckDB, path as a table duckdb.sql("SELECT * FROM 'data/sales.csv'")
read many files as one table glob + union_by_name read_csv('data/reports/*.csv', union_by_name = true)
query a pandas or Polars frame DuckDB, frame variable as a table duckdb.sql("SELECT ... FROM sales_df")
open a SQLite file in DuckDB ATTACH ATTACH 'data/shop.db' AS shop (TYPE sqlite, READ_ONLY)
result as a pandas / Polars frame .df() / .pl() duckdb.sql(sql).pl()
SQLite → pandas pd.read_sql_query pd.read_sql_query(sql, con, params=(...,))
print a DuckDB result narrowly .show(max_width=100) rel.show(max_width=100)
keep rows by condition WHERE WHERE region = 'East' AND unit_price >= 100
keep groups by condition HAVING HAVING COUNT(*) > 500
count rows / non-null values / distinct COUNT(*), COUNT(col), COUNT(DISTINCT col) COUNT(DISTINCT order_id)
aggregate some rows only FILTER (WHERE ...) SUM(revenue) FILTER (WHERE channel = 'online')
replace NULL COALESCE COALESCE(discount, 0)
avoid division by zero NULLIF revenue / NULLIF(quantity, 0)
bucket values CASE WHEN CASE WHEN x < 30 THEN 'low' ELSE 'high' END
rows without a match anti-join WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)
name the steps of a query CTE WITH monthly AS (...), ranked AS (...) SELECT ...
top N per group ROW_NUMBER() + QUALIFY (DuckDB) QUALIFY ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) <= 3
running total SUM() OVER (ORDER BY ...) SUM(revenue) OVER (ORDER BY month)
previous row’s value LAG LAG(revenue) OVER (ORDER BY month)
moving average a ROWS frame AVG(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
share of the total an empty window revenue / SUM(revenue) OVER ()
month label strftime SQLite strftime('%Y-%m', d), DuckDB strftime(d, '%Y-%m')
long → wide conditional aggregation, DuckDB PIVOT PIVOT sales ON channel USING SUM(quantity)
list the tables sqlite_schema, DuckDB SHOW TABLES SELECT name FROM sqlite_schema WHERE type = 'table'
describe a table pragma_table_info, DuckDB DESCRIBE DESCRIBE SELECT * FROM 'data/stores.csv'
save a result to Parquet DuckDB COPY ... TO COPY (SELECT ...) TO 'out.parquet' (FORMAT parquet)
import sqlite3
import duckdb
import pandas as pd
import polars as pl
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
pl.Config.set_tbl_width_chars(100)
pl.Config.set_fmt_float("full")
con = sqlite3.connect("file:data/shop.db?mode=ro", uri=True) # SQLite, read-only
ddb = duckdb.connect() # DuckDB, in memory
ddb.sql("ATTACH 'data/shop.db' AS shop (TYPE sqlite, READ_ONLY)") # the same file
ddb.sql("CREATE VIEW sales AS SELECT * FROM 'data/sales.csv'") # a CSV as a table
tables = "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
print([name for (name,) in con.execute(tables)])
print(ddb.sql("SELECT COUNT(*) FROM shop.orders").fetchall())
print(ddb.sql("SELECT order_date FROM sales").types) # DuckDB detects real dates
Output
['customers', 'orders', 'products', 'stores']
[(20228,)]
[DATE]

You write SELECT first, but the database runs it fifth. The logical order explains most errors: WHERE cannot see aggregates, and window results do not exist until SELECT runs.

SELECT region, COUNT(*) AS lines -- written 1, runs 5
FROM orders AS o -- written 2, runs 1
JOIN stores AS s USING (store_id) -- written 3, runs 1
WHERE o.order_date >= '2024-01-01' -- written 4, runs 2
GROUP BY region -- written 5, runs 3
HAVING COUNT(*) > 1000 -- written 6, runs 4
ORDER BY lines DESC -- written 7, runs 7
LIMIT 3; -- written 8, runs 8
flowchart LR
    F["FROM / JOIN"] --> W["WHERE"] --> G["GROUP BY"] --> H["HAVING"]
    H --> S["SELECT + windows"] --> Q["QUALIFY"] --> O["ORDER BY"] --> L["LIMIT"]
Logical step Clause Does Sees aggregates Sees window results Sees SELECT aliases
1 FROM, JOIN build the rows from tables no no no
2 WHERE drop rows no no no (yes in SQLite and DuckDB)
3 GROUP BY form groups no no yes in SQLite and DuckDB
4 HAVING drop groups yes no yes in SQLite and DuckDB
5 SELECT compute columns, then window functions yes defines them —
5 DISTINCT drop duplicate output rows — — —
6 QUALIFY (DuckDB) drop rows by a window result yes yes yes
7 ORDER BY sort yes yes yes
8 LIMIT n OFFSET m cut — — —
con.execute("SELECT region, COUNT(*) FROM stores WHERE COUNT(*) > 2 GROUP BY region")
Output
sqlite3.OperationalError: misuse of aggregate: COUNT()
fixed = """SELECT region, ROUND(AVG(size_sqm)) AS avg_sqm FROM stores
GROUP BY region HAVING avg_sqm > 2000 ORDER BY region"""
print(con.execute(fixed).fetchall()) # HAVING sees aggregates (and, here, aliases)
Output
[('East', 2403.0), ('North', 2073.0), ('South', 2360.0)]
Operator or function Meaning Note
=, <> / !=, <, <=, >, >= compare text in single quotes: 'East'
AND, OR, NOT logic AND binds tighter than OR: add parentheses
IN ('a', 'b'), NOT IN (...) membership NOT IN with a NULL in the list returns no rows
BETWEEN a AND b inclusive range for dates prefer >= a AND < b
LIKE 'Run%', _ % any text, _ one character SQLite: ignores ASCII case; DuckDB: case-sensitive, ILIKE ignores case
IS NULL, IS NOT NULL missing test never = NULL
COALESCE(a, b, ...) first non-NULL like fillna
NULLIF(a, b) NULL if a = b x / NULLIF(y, 0)
CAST(x AS REAL), x::DOUBLE, TRY_CAST(x AS INTEGER) convert type :: and TRY_CAST are DuckDB
a || b join text NULL || 'x' is NULL; DuckDB concat() skips NULLs
lower, upper, trim, length, substr(s, start, n), replace text functions both engines; positions start at 1
ROUND(x, 2) round half away from zero Python’s round rounds half to even
7 / 2 division SQLite 3 (integers), DuckDB 3.5; DuckDB 7 // 2 is 3
SELECT DISTINCT a, b unique rows applies to the whole output row
ORDER BY x DESC NULLS LAST sort SQLite: NULL is the smallest value (first in ASC, last in DESC); DuckDB: last in both
Expression Result Why
NULL = NULL, NULL <> 1, 1 + NULL NULL unknown in, unknown out
NULL IS NULL true the only safe test
NULL OR TRUE, NULL AND FALSE true, false three-valued logic
WHERE cond keeps true rows only false and NULL rows are dropped
COUNT(*) vs COUNT(col) all rows vs non-NULL values
SUM, AVG, MIN, MAX skip NULLs SUM of only NULLs is NULL
GROUP BY col all NULLs form one group
Join Keeps Missing side pandas Polars
[INNER] JOIN ... ON a.k = b.k matching pairs — merge(how="inner") join(how="inner")
LEFT JOIN every left row right columns NULL how="left" how="left"
RIGHT JOIN every right row left columns NULL how="right" how="right"
FULL [OUTER] JOIN every row of both NULL on the missing side how="outer" how="full"
CROSS JOIN every pair (n × m) — how="cross" how="cross"
WHERE EXISTS (subquery) left rows with a match, once — df[df.k.isin(o.k)] how="semi"
WHERE NOT EXISTS (subquery) left rows without a match — df[~df.k.isin(o.k)] how="anti"
LEFT JOIN ... WHERE b.k IS NULL left rows without a match — merge(indicator=True) how="anti"
self-join t AS a JOIN t AS b pairs inside one table — df.merge(df, ...) df.join(df, ...)
USING (k) ON a.k = b.k, one k column — on="k" on="k"

RIGHT and FULL joins need SQLite 3.39 or later; check sqlite3.sqlite_version (the course environment has 3.50). A join returns one row per matching pair: a key that repeats on the right side multiplies the left rows.

never = """
SELECT COUNT(*) FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.customer_id IS NULL
"""
not_exists = """
SELECT COUNT(*) FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id)
"""
not_in_null = """
SELECT COUNT(*) FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders UNION ALL SELECT NULL)
"""
fan_out = "SELECT COUNT(*) FROM stores JOIN stores AS s2 USING (region)"
for sql in [never, not_exists, not_in_null, fan_out]:
print(con.execute(sql).fetchone())
Output
(1746,)
(1746,)
(0,)
(36,)

The two anti-joins agree. One NULL in the NOT IN list makes every comparison unknown, so no row passes. The self-join on a non-unique key turns 12 stores into 36 rows.

Function Returns Engines
COUNT(*), COUNT(col), COUNT(DISTINCT col) rows, non-NULL values, distinct values both
SUM, AVG, MIN, MAX total, mean, extremes both
AVG(flag) on a 0/1 column a rate both
agg(x) FILTER (WHERE cond) aggregate only some rows both
SUM(CASE WHEN cond THEN x END) the same, portable to every database both
group_concat(x, ','), string_agg(x, ',') join text both (string_agg in SQLite 3.44+)
median(x), quantile_cont(x, 0.9), mode(x) median, percentile, most common DuckDB
arg_max(id, value), arg_min(id, value) id of the row with the largest / smallest value DuckDB
GROUP BY ALL group by every non-aggregated column DuckDB
ORDER BY ALL sort by every output column, left to right DuckDB
ANY_VALUE(col) any value of the group DuckDB (SQLite allows a bare column)
churn = """
SELECT plan,
COUNT(*) AS customers,
ROUND(100.0 * AVG(churned), 1) AS churn_pct,
COUNT(*) FILTER (WHERE contract = 'month-to-month') AS monthly,
SUM(CASE WHEN has_autopay = 1 THEN 1 ELSE 0 END) AS autopay
FROM customers
WHERE tenure_months >= 12
GROUP BY plan
HAVING COUNT(*) > 100
ORDER BY churn_pct DESC
"""
print(pd.read_sql_query(churn, con))
Output
plan customers churn_pct monthly autopay
0 premium 653 18.4 250 335
1 basic 1245 8.8 520 634
2 standard 1262 8.2 482 691
ddb.sql("""
SELECT region,
arg_max(product, revenue) AS biggest_line,
median(revenue) AS median_rev,
ROUND(quantile_cont(revenue, 0.9), 2) AS p90_rev,
string_agg(DISTINCT channel, '/' ORDER BY channel) AS channels
FROM sales
GROUP BY ALL
ORDER BY ALL
""").show(max_width=100)
ddb.sql("PIVOT sales ON channel USING SUM(quantity) GROUP BY region ORDER BY 1").show()
Output
┌─────────┬──────────────────────────┬────────────┬─────────┬──────────────┐
│ region │ biggest_line │ median_rev │ p90_rev │ channels │
│ varchar │ varchar │ double │ double │ varchar │
├─────────┼──────────────────────────┼────────────┼─────────┼──────────────┤
│ East │ 14-inch Ultrabook Laptop │ 79.99 │ 349.0 │ online/store │
│ North │ 55-inch 4K Smart TV │ 79.99 │ 340.2 │ online/store │
│ South │ 14-inch Ultrabook Laptop │ 79.99 │ 336.87 │ online/store │
│ West │ 14-inch Ultrabook Laptop │ 79.99 │ 348.66 │ online/store │
└─────────┴──────────────────────────┴────────────┴─────────┴──────────────┘
┌─────────┬────────┬────────┐
│ region │ online │ store │
│ varchar │ int128 │ int128 │
├─────────┼────────┼────────┤
│ East │ 3302 │ 4530 │
│ North │ 3179 │ 4133 │
│ South │ 3117 │ 4378 │
│ West │ 2850 │ 4044 │
└─────────┴────────┴────────┘
Form Syntax Use
searched CASE WHEN c1 THEN a WHEN c2 THEN b ELSE d END ranges and any condition; the first true branch wins
simple CASE col WHEN 'x' THEN a WHEN 'y' THEN b END map fixed values
no ELSE CASE WHEN c THEN a END NULL when nothing matches; SUM and COUNT skip it
inside an aggregate SUM(CASE WHEN channel = 'online' THEN revenue ELSE 0 END) pivot categories into columns
in ORDER BY ORDER BY CASE plan WHEN 'premium' THEN 1 ELSE 2 END a custom sort order
SQLite shortcut iif(cond, a, b) one condition
bands = """
SELECT CASE WHEN unit_price < 30 THEN 'budget'
WHEN unit_price < 150 THEN 'mid'
ELSE 'premium' END AS band,
COUNT(*) AS products,
ROUND(AVG(unit_price - unit_cost), 2) AS avg_margin
FROM products
GROUP BY band
ORDER BY CASE band WHEN 'budget' THEN 1 WHEN 'mid' THEN 2 ELSE 3 END
"""
print(con.execute(bands).fetchall())
Output
[('budget', 9, 14.3), ('mid', 12, 49.84), ('premium', 9, 199.66)]

A CTE (common table expression) names a query step with WITH name AS (...). Each step can read the steps before it, so a long query reads top to bottom.

Form Example Returns
scalar subquery WHERE unit_price > (SELECT AVG(unit_price) FROM products) one value
IN subquery WHERE store_id IN (SELECT store_id FROM stores WHERE region = 'West') a list
correlated subquery WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id) runs per outer row
derived table FROM (SELECT ...) AS t a table
CTE WITH t AS (SELECT ...) SELECT ... FROM t a named table
chained CTEs WITH a AS (...), b AS (SELECT ... FROM a) SELECT ... FROM b steps
recursive CTE WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 5) a generated series
mom = """
WITH monthly AS (
SELECT date_trunc('month', order_date)::DATE AS month, SUM(revenue) AS revenue
FROM sales
GROUP BY month
),
lagged AS (
SELECT month, revenue, LAG(revenue) OVER (ORDER BY month) AS prev
FROM monthly
)
SELECT month, ROUND(revenue, 2) AS revenue,
ROUND(100 * (revenue / prev - 1), 1) AS mom_pct
FROM lagged
WHERE month >= DATE '2024-10-01' -- filter after the window, not before
ORDER BY month
"""
ddb.sql(mom).show()
Output
┌────────────┬───────────┬─────────┐
│ month │ revenue │ mom_pct │
│ date │ double │ double │
├────────────┼───────────┼─────────┤
│ 2024-10-01 │ 166147.92 │ 17.3 │
│ 2024-11-01 │ 268466.55 │ 61.6 │
│ 2024-12-01 │ 302911.77 │ 12.8 │
└────────────┴───────────┴─────────┘

A window function computes a value from a set of rows related to the current row, without merging the rows. The row count does not change.

function(args) OVER (
PARTITION BY group_cols -- separate windows (optional)
ORDER BY sort_cols -- order inside each window
ROWS BETWEEN start AND end -- the frame (optional)
)
Function Gives Note
ROW_NUMBER() 1, 2, 3, 4 ties broken arbitrarily: add a tie-break column
RANK() 1, 2, 2, 4 ties share a rank, then a gap
DENSE_RANK() 1, 2, 2, 3 ties share a rank, no gap
NTILE(4) bucket 1–4 quartiles
PERCENT_RANK(), CUME_DIST() relative position 0–1
LAG(x), LAG(x, 12), LEAD(x) the previous, 12th previous, next value NULL at the edges; LAG(x, 1, 0) sets a default
FIRST_VALUE(x), LAST_VALUE(x) first / last value in the frame LAST_VALUE needs a full frame
SUM(x) OVER (ORDER BY t) running total default frame includes ties
SUM(x) OVER () grand total on every row
AVG(x) OVER (PARTITION BY g) group mean on every row pandas transform("mean"), Polars .over("g")
Frame Rows the function sees
no ORDER BY the whole partition
ORDER BY, no frame RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: up to the current row and its ties
ROWS UNBOUNDED PRECEDING up to the current row, no ties
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW a 7-row moving window
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING a centered 3-row window
RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW the last 7 calendar days (DuckDB)
top2 = """
WITH region_product AS (
SELECT region, product, ROUND(SUM(revenue), 2) AS revenue
FROM sales
GROUP BY ALL
)
SELECT region, product, revenue,
ROUND(100 * revenue / SUM(revenue) OVER (PARTITION BY region), 1) AS pct
FROM region_product
QUALIFY ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC, product) <= 2
ORDER BY region, revenue DESC
"""
ddb.sql(top2).show(max_width=100)
Output
┌─────────┬──────────────────────────┬───────────┬────────┐
│ region │ product │ revenue │ pct │
│ varchar │ varchar │ double │ double │
├─────────┼──────────────────────────┼───────────┼────────┤
│ East │ 55-inch 4K Smart TV │ 195239.7 │ 19.6 │
│ East │ 14-inch Ultrabook Laptop │ 192687.3 │ 19.4 │
│ North │ 55-inch 4K Smart TV │ 162504.9 │ 18.3 │
│ North │ 14-inch Ultrabook Laptop │ 145291.05 │ 16.4 │
│ South │ 14-inch Ultrabook Laptop │ 165398.55 │ 18.5 │
│ South │ 55-inch 4K Smart TV │ 136849.65 │ 15.3 │
│ West │ 14-inch Ultrabook Laptop │ 161951.55 │ 19.7 │
│ West │ 55-inch 4K Smart TV │ 133991.85 │ 16.3 │
└─────────┴──────────────────────────┴───────────┴────────┘
mem = sqlite3.connect(":memory:")
mem.execute("CREATE TABLE m (month TEXT, revenue REAL)")
mem.executemany("INSERT INTO m VALUES (?, ?)", [("01", 10), ("02", 30), ("03", 20)])
win = """
SELECT month, revenue,
SUM(revenue) OVER (ORDER BY month) AS running,
LAG(revenue) OVER (ORDER BY month) AS prev,
RANK() OVER (ORDER BY revenue DESC) AS rnk,
AVG(revenue) OVER (ORDER BY month ROWS 1 PRECEDING) AS ma2 -- this + previous
FROM m ORDER BY month
"""
for row in mem.execute(win):
print(row)
mem.close()
Output
('01', 10.0, 10.0, None, 3, 10.0)
('02', 30.0, 40.0, 10.0, 1, 20.0)
('03', 20.0, 60.0, 30.0, 2, 25.0)

SQLite has no QUALIFY: filter on a window result in an outer query (SELECT * FROM (... ) WHERE rn <= 2) or a CTE.

SQLite has no date type: store dates as ISO text ('2024-05-01'), which sorts and compares correctly. DuckDB has real DATE, TIMESTAMP and INTERVAL types.

Task SQLite (text dates) DuckDB (DATE, TIMESTAMP)
literal '2024-05-01' DATE '2024-05-01', '2024-05-01'::DATE
today date('now') current_date
parse other formats not built in: store ISO text strptime('05/01/2024', '%m/%d/%Y') (a TIMESTAMP)
year, month as numbers CAST(strftime('%Y', d) AS INTEGER) year(d), month(d), quarter(d)
month label strftime('%Y-%m', d) (format first) strftime(d, '%Y-%m') (date first)
first of month date(d, 'start of month') date_trunc('month', d) (a TIMESTAMP; add ::DATE)
last of month date(d, 'start of month', '+1 month', '-1 day') last_day(d)
add days / months date(d, '+7 days'), date(d, '+1 month') d + 7 (a DATE), d + INTERVAL 1 MONTH (a TIMESTAMP)
Jan 31 + 1 month 2024-03-02 (rolls over) 2024-02-29 (clamps to the month end)
days between julianday(b) - julianday(a) (a float) date_diff('day', a, b) or b - a
day of week strftime('%w', d): '0' = Sunday, as text dayofweek(d): 0 = Sunday; isodow(d): 1 = Monday
day / month name not built in dayname(d), monthname(d)
one year d >= '2024-01-01' AND d < '2025-01-01' the same, or year(d) = 2024
a calendar of days recursive CTE generate_series(DATE '2024-01-01', DATE '2024-01-31', INTERVAL 1 DAY)
lite = """SELECT strftime('%Y-%m', '2024-01-31'), -- month label
date('2024-01-31', '+1 month'), -- add a month
strftime('%w', '2024-05-05'), -- day of week (a Sunday)
julianday('2024-03-01') - julianday('2024-01-01'), -- days between
date('2024-05-17', 'start of month')"""
duck = """SELECT strftime(DATE '2024-01-31', '%Y-%m'),
DATE '2024-01-31' + INTERVAL 1 MONTH,
dayofweek(DATE '2024-05-05'),
date_diff('day', DATE '2024-01-01', DATE '2024-03-01'),
date_trunc('month', DATE '2024-05-17')"""
print(con.execute(lite).fetchone())
print(ddb.sql(duck).fetchall()[0])
print(con.execute("SELECT strftime('2024-05-05', '%Y')").fetchone()) # wrong order
Output
('2024-01', '2024-03-02', '0', 60.0, '2024-05-01')
('2024-01', datetime.datetime(2024, 2, 29, 0, 0), 0, 60, datetime.datetime(2024, 5, 1, 0, 0))
(None,)
Call Does
sqlite3.connect("shop.db") open or create a file
sqlite3.connect("file:shop.db?mode=ro", uri=True) open read-only; fails if the file is missing
sqlite3.connect(":memory:") a database in memory
sqlite3.connect(p, autocommit=False) Python 3.12+: every change is in a transaction, CREATE and DROP too
con.execute(sql, params) run one statement; returns a cursor
con.executemany(sql, rows) run one statement per row
con.executescript(sql) run several statements (never with user input)
cur.fetchone(), cur.fetchmany(n), cur.fetchall(), for row in cur: read rows as tuples
cur.description column names: [c[0] for c in cur.description]
con.row_factory = sqlite3.Row rows that also work like dicts: row["city"]
with con: commit on success, roll back on an exception; does not close
con.commit(), con.rollback(), con.close() transactions and cleanup
con.backup(other), con.iterdump() copy a database; dump it as SQL
contextlib.closing(sqlite3.connect(p)) a with block that closes
from contextlib import closing
with closing(sqlite3.connect(":memory:", autocommit=False)) as mem:
mem.row_factory = sqlite3.Row
with mem: # one transaction: commit at the end, roll back on an error
mem.execute("CREATE TABLE targets (store_id TEXT PRIMARY KEY, target REAL)")
rows = [("S01", 90_000.0), ("S02", 70_000.0)]
mem.executemany("INSERT INTO targets VALUES (?, ?)", rows)
cur = mem.execute("SELECT store_id, target FROM targets ORDER BY target DESC")
print([c[0] for c in cur.description])
row = cur.fetchone()
print(row["store_id"], row["target"], dict(row))
print(cur.fetchall()[0][0]) # rows still index by position
Output
['store_id', 'target']
S01 90000.0 {'store_id': 'S01', 'target': 90000.0}
S02
Call Does
duckdb.sql(sql) run on the default in-memory connection; returns a relation
duckdb.connect(), duckdb.connect("file.duckdb", read_only=True) a connection in memory / to a file
ddb.sql(sql, params=...) a relation: a lazy query; runs when you fetch
rel.fetchall(), rel.df(), rel.pl(), rel.fetchnumpy() results as tuples, pandas, Polars, NumPy
rel.show(max_width=100), rel.columns, rel.types, rel.shape inspect
rel.limit(5).fetchall() the first rows (relations have no fetchone or fetchmany in DuckDB 2)
rel.filter("x > 0").aggregate("COUNT(*)"), .order("x"), .project("a, b") the relational API: build a query with methods
ddb.sql("SELECT * FROM rel") a relation variable can be queried by name
ddb.execute(sql, params) a DB-API style call; then fetchone, fetchall, df() on the connection
ddb.complete(), ddb.abort() finish or drop an unfinished execute result (DuckDB 2)
ddb.register("name", df) expose a DataFrame under a table name
rel.write_parquet(p), rel.write_csv(p), COPY (...) TO p (FORMAT parquet) save a result
ddb.sql("ATTACH 'x.db' AS x (TYPE sqlite, READ_ONLY)") read a SQLite file (the extension downloads once)
read_csv(p, union_by_name = true, filename = true) many files; add the file name as a column
rel = ddb.sql("SELECT store_id, city, size_sqm FROM 'data/stores.csv'")
print(rel.shape, rel.columns, [str(t) for t in rel.types])
big = rel.filter("size_sqm > 2500").order("size_sqm DESC") # still lazy
print(big.limit(2).fetchall())
print(ddb.sql("SELECT COUNT(*) AS n FROM big").fetchall()) # query a relation by name
print(type(big.df()).__name__, big.pl().schema)
big.write_parquet("big_stores.parquet")
print(ddb.sql("SELECT COUNT(*) FROM 'big_stores.parquet'").fetchall())
Output
(12, 3) ['store_id', 'city', 'size_sqm'] ['VARCHAR', 'VARCHAR', 'BIGINT']
[('S07', 'New York', 3400), ('S04', 'Houston', 3100)]
[(3,)]
DataFrame Schema({'store_id': String, 'city': String, 'size_sqm': Int64})
[(3,)]

In DuckDB 2 a connection keeps the result of execute() until you fetch every row. A half-read result blocks sql() on that connection:

print(ddb.execute("SELECT * FROM range(3)").fetchone()) # one row of three read
ddb.sql("SELECT 1").fetchall()
Output
(0,)
_duckdb.ResourceInUseException: Resource In Use Error: connection has an unfinished result from execute(); call complete() or abort(), or fetch until a fetch returns no rows, before other work on this connection, or use a separate connection from cursor()
ddb.abort() # drop the unfinished result (or fetchall(), or ddb.complete())
print(ddb.sql("SELECT 1").fetchall())
Output
[(1,)]

Never build SQL with f-strings or + from values you did not write. A placeholder sends the value separately from the SQL text, so it can never change the query.

Driver Positional Named Values
sqlite3 ? :name a tuple ((x,) for one) / a dict
DuckDB ? or $1 $name a list / a dict, params= in sql()
pd.read_sql_query + sqlite3 ? :name params=(...) / params={...}
pl.read_database the driver’s style execute_options={"parameters": ...}
attack = "x' OR '1'='1"
unsafe = f"SELECT COUNT(*) FROM customers WHERE customer_id = '{attack}'"
print(con.execute(unsafe).fetchone()) # injected: matches every row
safe = "SELECT COUNT(*) FROM customers WHERE customer_id = ?"
print(con.execute(safe, (attack,)).fetchone()) # the value stays a value
named = "SELECT COUNT(*) FROM orders WHERE order_date >= :start AND store_id = :store"
print(con.execute(named, {"start": "2024-01-01", "store": "S01"}).fetchone())
west = ddb.sql("SELECT COUNT(*) FROM sales WHERE region = $r", params={"r": "West"})
print(west.fetchall()) # DuckDB: $name and a dict
ALLOWED = {"region", "channel", "category"} # identifiers cannot be parameters
def revenue_by(column: str) -> list[tuple]:
if column not in ALLOWED:
raise ValueError(f"unknown column: {column!r}")
sql = f"SELECT {column}, ROUND(SUM(revenue)) FROM sales GROUP BY 1 ORDER BY 1"
return ddb.sql(sql).fetchall()
print(revenue_by("channel"))
Output
(5000,)
(0,)
(1254,)
[(4722,)]
[('online', 1519466.0), ('store', 2077057.0)]
SQL pandas Polars
SELECT a, b FROM t t[["a", "b"]] t.select("a", "b")
SELECT *, a * 2 AS c t.assign(c=t["a"] * 2) t.with_columns(c=pl.col("a") * 2)
WHERE x > 5 AND y = 'A' t.query("x > 5 and y == 'A'") t.filter(pl.col("x") > 5, pl.col("y") == "A")
WHERE k IN ('a', 'b') t[t["k"].isin(["a", "b"])] t.filter(pl.col("k").is_in(["a", "b"]))
WHERE x IS NULL t[t["x"].isna()] t.filter(pl.col("x").is_null())
ORDER BY x DESC LIMIT 3 t.nlargest(3, "x") t.top_k(3, by="x")
SELECT DISTINCT k t["k"].drop_duplicates() t.select("k").unique()
COUNT(*) ... GROUP BY k t.groupby("k").size() t.group_by("k").len()
SUM(x) ... GROUP BY k t.groupby("k")["x"].sum() t.group_by("k").agg(pl.col("x").sum())
HAVING COUNT(*) > 10 filter the aggregated frame .filter(pl.col("len") > 10) after len()
COUNT(DISTINCT k) t["k"].nunique() pl.col("k").n_unique()
LEFT JOIN u USING (k) t.merge(u, on="k", how="left") t.join(u, on="k", how="left")
WHERE NOT EXISTS (...) t[~t["k"].isin(u["k"])] t.join(u, on="k", how="anti")
CASE WHEN ... END np.where, np.select pl.when().then().otherwise()
COALESCE(x, 0) t["x"].fillna(0) pl.col("x").fill_null(0)
SUM(x) OVER (PARTITION BY g) t.groupby("g")["x"].transform("sum") pl.col("x").sum().over("g")
ROW_NUMBER() OVER (PARTITION BY g ORDER BY v DESC) t.groupby("g")["v"].rank(method="first", ascending=False) pl.col("v").rank("ordinal", descending=True).over("g")
SUM(v) OVER (PARTITION BY g ORDER BY d) t.sort_values("d").groupby("g")["v"].cumsum() pl.col("v").cum_sum().over("g", order_by="d")
LAG(v) OVER (PARTITION BY g ORDER BY d) t.sort_values("d").groupby("g")["v"].shift() pl.col("v").shift().over("g", order_by="d")
AVG(v) OVER (ORDER BY d ROWS 6 PRECEDING) t["v"].rolling(7, min_periods=1).mean() pl.col("v").rolling_mean(7, min_samples=1)
UNION ALL / UNION pd.concat([a, b]) / + .drop_duplicates() pl.concat([a, b]) / + .unique()
Direction Code
SQLite → pandas pd.read_sql_query(sql, con, params=(...), parse_dates=["order_date"])
SQLite → Polars pl.read_database(sql, connection=con)
pandas → SQLite df.to_sql("t", con, index=False, if_exists="replace") (returns the row count)
pandas or Polars → DuckDB duckdb.sql("SELECT ... FROM df"): the variable name is the table name
DuckDB → pandas / Polars rel.df() / rel.pl()
Polars → SQL on itself df.sql("SELECT ... FROM self")
orders = pd.read_sql_query(
"SELECT order_id, order_date, revenue FROM orders WHERE store_id = ? LIMIT 3",
con,
params=("S01",),
parse_dates=["order_date"],
)
print(orders.dtypes.astype(str).to_dict())
stores_pl = pl.read_database("SELECT store_id, region FROM stores", connection=con)
counts = duckdb.sql("SELECT region, COUNT(*) FROM stores_pl GROUP BY ALL ORDER BY 1")
print(counts.pl().rows()) # a Polars frame queried by its variable name
mem = sqlite3.connect(":memory:")
print(orders.to_sql("orders", mem, index=False)) # rows written
print(mem.execute("SELECT typeof(order_date) FROM orders").fetchone()) # dates: text
mem.close()
con.close()
Output
{'order_id': 'str', 'order_date': 'datetime64[us]', 'revenue': 'float64'}
[('East', 3), ('North', 3), ('South', 3), ('West', 3)]
3
('text',)
Topic SQLite DuckDB
install standard library (import sqlite3) pip install duckdb
workload OLTP: many small reads and writes, apps OLAP: scans and aggregations, analysis
storage rows, one .db file columns, a .duckdb file or memory
files none CSV, Parquet, JSON, globs, DataFrames
types flexible (type affinity), no DATE, no Boolean strict: DATE, TIMESTAMP, BOOLEAN, lists, structs
"text" in double quotes a string if no such column exists always a column name: Binder Error
7 / 2 3 3.5 (7 // 2 is 3)
LIKE ignores ASCII case case-sensitive; ILIKE ignores case
column not in GROUP BY allowed, value from any row Binder Error; use ANY_VALUE(col)
extras iif, julianday QUALIFY, GROUP BY ALL, PIVOT, EXCLUDE, arg_max, median
NULLs in ORDER BY first (ASC) / last (DESC) last
Trap Symptom Fix
WHERE col = NULL no rows IS NULL
NOT IN (subquery) with a NULL inside no rows NOT EXISTS
SQLite integer division SUM(flag) * 100 / COUNT(*) gives whole numbers write 100.0, or CAST(... AS REAL)
a filter on the right table of a LEFT JOIN in WHERE unmatched left rows vanish (an inner join) move the condition into ON
a join to a non-unique key rows multiply; sums inflate (fan-out) join to a primary key, or aggregate first
an aggregate in WHERE misuse of aggregate (SQLite), Binder Error (DuckDB) HAVING
a window result in WHERE error, or rows that LAG needs are gone filter in an outer query, or QUALIFY in DuckDB
ROW_NUMBER() with tied sort values a different row wins on each run add a tie-break column to ORDER BY
running total over raw lines jumps by whole days: the default frame includes ties aggregate to one row per key, or use ROWS
BETWEEN '2024-01-01' AND '2024-01-31' on timestamp text rows later on January 31 are missing >= '2024-01-01' AND < '2024-02-01'
SQLite strftime(d, '%Y') NULL the format comes first in SQLite: strftime('%Y', d)
month arithmetic SQLite Jan 31 + 1 month = March 2; DuckDB = February 29 test month ends; use start of month before adding
DuckDB date_trunc or + INTERVAL on a date a TIMESTAMP, printed with 00:00:00 cast back: date_trunc('month', d)::DATE
f-strings with user input SQL injection placeholders; allowlist table and column names
execute("... WHERE id = ?", cid) ProgrammingError a tuple: (cid,)
execute("SELECT 1; SELECT 2") ProgrammingError: You can only execute one statement at a time one statement per call
with sqlite3.connect(p) as con: the file stays open it only commits; call con.close() or use closing()
sqlite3.connect("data/shop.db") to read a typo in the path creates an empty database "file:...?mode=ro", uri=True
DuckDB rel.fetchone(), rel.fetchmany() AttributeError in DuckDB 2 rel.limit(1).fetchall(), .pl().item(), .df()
a half-read ddb.execute() result ResourceInUseException on the next ddb.sql() fetch all rows, ddb.complete() / ddb.abort(), or ddb.cursor()
ddb.execute(...).pl() AttributeError: connections have no pl() ddb.sql(...).pl()
DuckDB SUM of an integer column type HUGEINT (int128): pandas gets float64, Polars Decimal(38, 0) SUM(quantity)::BIGINT
print(rel) of a wide DuckDB result lines wider than the screen rel.show(max_width=100)
df.to_sql without index=False an extra index column index=False
dates written by to_sql to SQLite text such as 2023-01-01 00:00:00 parse_dates= when you read them back

Every scikit-learn object follows one small contract: settings go into __init__, fit learns from data, and the other methods use what fit learned. This page covers that contract, pipelines, column-wise preprocessing, pandas output, custom estimators and saving models. The examples use data/customers.csv (churn). The blocks share one session:

import numpy as np
import pandas as pd
import sklearn
from sklearn.model_selection import train_test_split
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
X = customers.drop(columns=["customer_id", "signup_date", "churned"])
y = customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
I want to… Use… Notes
learn from data est.fit(X, y) returns est, so calls chain
apply a learned transformation est.transform(X) transformers only
fit and transform training rows est.fit_transform(X_train) never on test rows
predict labels or numbers est.predict(X) classifiers, regressors
predict class probabilities est.predict_proba(X)[:, 1] columns follow est.classes_
get a ranking score est.decision_function(X) linear models, SVMs
get the default score est.score(X, y) accuracy or R²
read or change hyperparameters est.get_params(), est.set_params(C=0.1) set_params returns est
an unfitted copy with the same settings sklearn.base.clone(est)
a fitted copy copy.deepcopy(est) clone drops what was learned
check that a model is fitted check_is_fitted(est) raises NotFittedError
know the input columns est.feature_names_in_, est.n_features_in_ set by fit
know the output columns est.get_feature_names_out() transformers and pipelines
chain steps Pipeline([("name", step), ...]), make_pipeline(...) last step: any estimator
set a parameter inside a pipeline pipe.set_params(model__C=0.1) step__param, double underscore
list every valid parameter name sorted(pipe.get_params())
reach a step pipe["model"], pipe[-1], pipe.named_steps.model
the preprocessing part only pipe[:-1] a new Pipeline sharing fitted steps
skip a step (in a search) pipe.set_params(scale="passthrough")
cache slow steps Pipeline(steps, memory="cache_dir") for searches over the last step
put features side by side FeatureUnion([...]), make_union(...) outputs are concatenated
different steps per column group ColumnTransformer([(name, step, cols), ...])
select columns by dtype make_column_selector(dtype_include="number") "str" for pandas 3 text
select columns by name make_column_selector(pattern="^log_") a regular expression
keep the other columns ColumnTransformer(..., remainder="passthrough") default "drop"
short output names verbose_feature_names_out=False age, not num__age
DataFrames out of transformers est.set_output(transform="pandas") before fit; "polars" also works
pandas output everywhere sklearn.set_config(transform_output="pandas") or with sklearn.config_context(...)
a plain function as a step FunctionTransformer(np.log1p, feature_names_out="one-to-one") stateless
model a transformed target TransformedTargetRegressor(regressor, func=np.log, inverse_func=np.exp) predictions in original units
write a transformer class T(TransformerMixin, BaseEstimator) mixins first
write a classifier class C(ClassifierMixin, BaseEstimator) set classes_ in fit
validate input in my estimator validate_data(self, X); later reset=False sklearn.utils.validation
test my estimator check_estimator(est), @parametrize_with_checks([...]) dozens of checks (80 for Ridge)
route sample_weight through a search or pipeline set_config(enable_metadata_routing=True), model.set_fit_request(sample_weight=True).set_score_request(sample_weight=True) every consumer must state its request
use a prefit model inside a meta-estimator CalibratedClassifierCV(FrozenEstimator(fitted)) from sklearn.frozen import FrozenEstimator
save a fitted pipeline joblib.dump(pipe, "output/model.joblib") trusted files only
save without pickle risks skops.io.dump(pipe, "model.skops") load with a trusted-types list
Kind Mixin Main methods Examples
transformer TransformerMixin fit, transform, fit_transform StandardScaler, OneHotEncoder, SimpleImputer
classifier ClassifierMixin fit, predict, predict_proba, score (accuracy) LogisticRegression, RandomForestClassifier
regressor RegressorMixin fit, predict, score (R²) Ridge, HistGradientBoostingRegressor
clusterer ClusterMixin fit, fit_predict, labels_ KMeans, DBSCAN
outlier detector OutlierMixin fit_predict (−1 = outlier) IsolationForest
meta-estimator wraps another estimator the methods of what it wraps Pipeline, GridSearchCV, CalibratedClassifierCV
What Where Naming Example
hyperparameters __init__ arguments, stored unchanged no underscore C, max_depth, strategy
learned attributes set by fit trailing underscore coef_, mean_, classes_, categories_
input checks set by fit trailing underscore n_features_in_, feature_names_in_ (DataFrame input)
fit diagnostics set by fit trailing underscore n_iter_, best_params_, oob_score_
private state anything leading underscore _tree, _n_features_out
from sklearn.base import clone
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.utils.validation import check_is_fitted
num_cols = ["tenure_months", "monthly_charges", "support_tickets"]
model = LogisticRegression(C=0.5) # settings only; nothing learned yet
print(model, model.get_params()["C"]) # repr shows non-default settings
model.fit(X_train[num_cols], y_train)
print(model.classes_, model.coef_.round(3), model.n_features_in_)
fresh = clone(model) # same settings, not fitted
print(hasattr(fresh, "coef_"), fresh.set_params(C=2.0))
Output
LogisticRegression(C=0.5) 0.5
[0 1] [[-0.056 0.019 0.441]] 3
False LogisticRegression(C=2.0)
check_is_fitted(fresh) # predict, transform and score raise the same error
Output
sklearn.exceptions.NotFittedError: This LogisticRegression instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
pipe = Pipeline([
("impute", SimpleImputer(strategy="median")), # (name, estimator) pairs
("scale", StandardScaler()), # every step but the last is a transformer
("model", LogisticRegression(max_iter=1000)), # the last: any estimator
])
pipe.set_params(model__C=0.3, impute__strategy="mean") # step__param
pipe.fit(X_train[num_cols], y_train)
print([name for name, _ in pipe.steps], pipe["model"].C)
print(pipe[:-1].transform(X_test[num_cols].head(2)).round(2)) # preprocessing only
print(round(pipe.score(X_test[num_cols], y_test), 3))
print([n for n in pipe.get_params() if n.startswith("scale__")])
Output
['impute', 'scale', 'model'] 0.3
[[-0.62 -0.11 -1.07]
[-0.77 0.14 -1.07]]
0.825
['scale__copy', 'scale__with_mean', 'scale__with_std']
Call on a pipeline Runs
fit(X, y) fit_transform on each transformer in order, then fit on the last step
predict, predict_proba, score, decision_function transform on each transformer, then that method of the last step
transform(X) transform on every step (the last must be a transformer)
fit_transform(X, y) as fit, and returns the last step’s output
get_feature_names_out() output names of the last transformer
pipe[1:], pipe[:-1] a sub-pipeline that shares the fitted steps
set_params(step="passthrough") removes a step without rebuilding the pipeline
Builder Step names Use when
Pipeline([("a", A()), ("m", M())]) yours you tune or inspect steps by name
make_pipeline(A(), M()) lowercase class names: standardscaler quick pipelines
FeatureUnion([("a", A()), ("b", B())]) / make_union yours / automatic several feature sets from the same input
TransformedTargetRegressor(regressor=pipe, func=np.log, inverse_func=np.exp) regressor__... the target needs a transform
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.preprocessing import OneHotEncoder
prep = ColumnTransformer(
[
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
make_column_selector(dtype_include="number")), # int and float columns
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False),
make_column_selector(dtype_include="str")), # pandas 3 text columns
],
verbose_feature_names_out=False, # "age", not "num__age"
)
prep.set_output(transform="pandas") # before fit
Xt = prep.fit_transform(X_train)
print(Xt.shape, list(Xt.columns[:3]), Xt.columns[-1])
print(prep.named_transformers_["cat"].categories_[0]) # learned categories
clf = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(X_train, y_train)
print(round(clf.score(X_test, y_test), 3))
Output
(3750, 22) ['age', 'has_autopay', 'tenure_months'] payment_method_paypal
['East' 'North' 'South' 'West']
0.836
Column spec Selects
["age", "plan"] these names (DataFrame input)
"age" (a string, not a list) one column, passed as 1-D: only for text vectorizers
make_column_selector(dtype_include="number") numeric columns
make_column_selector(dtype_include="str") pandas 3 text columns (object warns)
make_column_selector(dtype_include="category") category columns
make_column_selector(dtype_exclude="number") everything that is not numeric
make_column_selector(pattern="charges$") names that match a regular expression
[0, 2], slice(0, 3), a boolean mask columns by position (NumPy input)
Option or attribute Meaning
remainder="drop" (default), "passthrough", or an estimator what happens to unlisted columns
"drop" or "passthrough" as a transformer drop or keep that group unchanged
sparse_threshold=0.3 the output is sparse when the share of nonzeros is below this
n_jobs fit the groups in parallel
transformers_, named_transformers_ the fitted groups
output_indices_ which output columns came from which group
make_column_transformer((step, cols), ...) the same with automatic names
Setting Scope Notes
est.set_output(transform="pandas") one estimator and its inner steps call it before fit
est.set_output(transform="polars") same needs polars installed
sklearn.set_config(transform_output="pandas") the whole process global state: affects every later estimator
with sklearn.config_context(transform_output="pandas"): one block restores the old value after the block
transform="default" NumPy arrays (or sparse) the default

Sparse outputs (for example OneHotEncoder() with its default sparse_output=True) cannot become DataFrames. Set sparse_output=False first.

with sklearn.config_context(transform_output="pandas"):
scaled = StandardScaler().fit_transform(X_train[num_cols]) # a DataFrame
print(type(scaled).__name__, list(scaled.columns))
print(sklearn.get_config()["transform_output"]) # back to the default
Output
DataFrame ['tenure_months', 'monthly_charges', 'support_tickets']
default
from sklearn.compose import TransformedTargetRegressor
from sklearn.linear_model import Ridge
from sklearn.preprocessing import FunctionTransformer
def add_charge_ratio(df: pd.DataFrame) -> pd.DataFrame:
"""Stateless: uses only the row itself, so nothing can leak."""
return df.assign(charge_ratio=df["total_charges"] / df["monthly_charges"])
def ratio_names(transformer, names):
return [*names, "charge_ratio"] # output names for get_feature_names_out
ratio = FunctionTransformer(add_charge_ratio, feature_names_out=ratio_names)
cols = ["monthly_charges", "total_charges"]
print(ratio.fit_transform(X_train[cols].head(2)))
print(ratio.get_feature_names_out(cols))
log_y = TransformedTargetRegressor(Ridge(), func=np.log1p, inverse_func=np.expm1)
log_y.fit(X_train[["tenure_months"]], X_train["monthly_charges"]) # fit on log1p(y)
print(log_y.predict(X_test[["tenure_months"]].head(2)).round(2)) # back in USD
Output
monthly_charges total_charges charge_ratio
53 29.09 1985.26 68.245
4249 55.95 220.18 3.935
['monthly_charges' 'total_charges' 'charge_ratio']
[56.69 56.68]
Need Tool
a fixed function of the features FunctionTransformer(func)
a function with arguments FunctionTransformer(np.clip, kw_args={"a_min": 0, "a_max": 100})
names for get_feature_names_out feature_names_out="one-to-one" or a callable (transformer, input_names) -> names
an inverse inverse_func=np.expm1; check_inverse=True (default) tests it on a sample
something learned from data (means, categories, quantiles) a real transformer, never FunctionTransformer
a transform of y TransformedTargetRegressor; regressor_ holds the fitted inner model

A transformer that groups rare categories (it learns the frequent ones in fit):

from sklearn.base import BaseEstimator, OneToOneFeatureMixin, TransformerMixin
from sklearn.utils.validation import validate_data
class RareGrouper(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
"""Replace categories seen fewer than min_count times with `other`."""
def __init__(self, min_count: int = 10, other: str = "other") -> None:
self.min_count = min_count # store arguments unchanged, same names
self.other = other
def fit(self, X, y=None): # y=None: pipelines pass y to every step
X = validate_data(self, X, dtype=None) # sets n_features_in_, names
self.keep_ = []
for col in X.T:
values, counts = np.unique(col, return_counts=True)
self.keep_.append(values[counts >= self.min_count])
return self # always return self
def transform(self, X):
check_is_fitted(self)
X = validate_data(self, X, dtype=None, reset=False) # same columns?
out = X.astype(object)
for j, keep in enumerate(self.keep_):
out[~np.isin(X[:, j], keep), j] = self.other
return out
towns = pd.DataFrame({"town": ["Oslo"] * 12 + ["Rome"] * 11 + ["Lima", "Kyiv"]})
grouper = RareGrouper().set_output(transform="pandas").fit(towns)
print(grouper.transform(towns)["town"].value_counts().to_dict())
print(grouper, grouper.get_feature_names_out(), clone(grouper).get_params())
Output
{'Oslo': 12, 'Rome': 11, 'other': 2}
RareGrouper() ['town'] {'min_count': 10, 'other': 'other'}

A classifier needs classes_, predict and, when it can, predict_proba:

from sklearn.base import ClassifierMixin
from sklearn.utils.multiclass import check_classification_targets
class NearestMean(ClassifierMixin, BaseEstimator):
"""Predict the class whose training mean is closest."""
def fit(self, X, y):
X, y = validate_data(self, X, y) # checks X and y together
check_classification_targets(y) # rejects a continuous y
self.classes_ = np.unique(y) # sorted labels: the column order
self.means_ = np.array([X[y == c].mean(axis=0) for c in self.classes_])
return self
def predict(self, X):
check_is_fitted(self)
X = validate_data(self, X, reset=False)
dist = ((X[:, None, :] - self.means_[None]) ** 2).sum(axis=2)
return self.classes_[dist.argmin(axis=1)]
nm = make_pipeline(StandardScaler(), NearestMean()).fit(X_train[num_cols], y_train)
print(nm[-1].classes_, round(nm.score(X_test[num_cols], y_test), 3)) # a template only
Output
[0 1] 0.676
Rule Why
__init__ only stores its arguments, with the same names get_params, set_params and clone read them back
validate hyperparameters in fit, not __init__ set_params would bypass checks in __init__
learned attributes end with _ and are set in fit check_is_fitted looks for them
fit returns self chaining and pipelines need it
fit(self, X, y=None) in transformers pipelines always pass y
mixins first, BaseEstimator last the method resolution order
validate_data(self, X) in fit, reset=False later sets and then checks n_features_in_ and feature_names_in_
no randomness without random_state use check_random_state(self.random_state) in fit
tags change behavior override __sklearn_tags__() (for example tags.input_tags.allow_nan = True)
Base class Adds
BaseEstimator get_params, set_params, repr, clone support, HTML display
TransformerMixin fit_transform; set_output when the class has get_feature_names_out
ClassifierMixin score = accuracy; marks a classifier (stratified cv=5)
RegressorMixin score = R²
OneToOneFeatureMixin get_feature_names_out = the input names
ClassNamePrefixFeaturesOutMixin get_feature_names_out = classname0, classname1, … (set _n_features_out)

Test a custom estimator against the full API contract with pytest:

test_estimators.py
from sklearn.utils.estimator_checks import parametrize_with_checks
from my_package.estimators import NearestMean, RareGrouper # importable module
@parametrize_with_checks([NearestMean(), RareGrouper()])
def test_sklearn_compatible(estimator, check):
check(estimator) # one pytest test per check
import json
from pathlib import Path
import joblib
Path("output").mkdir(exist_ok=True)
joblib.dump(clf, "output/churn.joblib") # the whole fitted pipeline
meta = {"sklearn": sklearn.__version__, "features": list(X_train.columns)}
Path("output/churn.json").write_text(json.dumps(meta)) # metadata next to it
loaded = joblib.load("output/churn.joblib") # only files you trust
print(np.array_equal(loaded.predict(X_test), clf.predict(X_test)))
Output
True
Format Save, load Safe for untrusted files? Notes
joblib (pickle) joblib.dump(m, path), joblib.load(path) no: loading runs code the default; same library versions to load
pickle pickle.dump, pickle.load no the same risks as joblib
skops skops.io.dump(m, path), skops.io.load(path, trusted=[...]) yes, with a reviewed type list skops.io.get_untrusted_types(file=path) lists what to review
ONNX skl2onnx.to_onnx(m, X[:1]), onnxruntime yes no Python or scikit-learn at serving time; not every estimator converts
XGBoost / LightGBM native model.save_model("m.json"), booster_.save_model("m.txt") yes stable across library versions; the booster only, not the pipeline
Caveat Fix
another scikit-learn version warns InconsistentVersionWarning and may predict differently pin the version; save it in the metadata; retrain on upgrade
custom classes defined in a notebook or __main__ cannot be found at load time put them in an importable module
a lambda in a FunctionTransformer cannot be pickled by pickle use a named function
loading a file from the internet runs arbitrary code load only your own files; use skops or ONNX to share
the model alone does not say what it expects store feature names, dtypes, metrics and the training date next to it
Trap Symptom Fix
fit_transform on test rows the test set gets its own statistics; scores look better than in production transform on everything but training rows
learned preprocessing outside the pipeline leakage in cross-validation put every learned step inside the pipeline
one underscore in a parameter name ValueError: Invalid parameter 'model_C' model__C; sorted(pipe.get_params()) lists valid names
set_output after fit a warning about feature names from inner steps call it before fit, or use config_context
make_column_selector(dtype_include=object) Pandas4Warning in pandas 3 dtype_include="str"
OneHotEncoder() meets a new category ValueError: Found unknown categories handle_unknown="ignore"
set_output(transform="pandas") with a sparse step ValueError about sparse output sparse_output=False
a column list as a string, "age" the step gets a 1-D input and fails ["age"]
a custom __init__ that renames or converts clone and get_params lose or change settings store each argument unchanged
fit without return self AttributeError: 'NoneType'... in a chain return self
clone(fitted) to copy a model the copy is unfitted copy.deepcopy or joblib
one transformer object in two pipelines the second fit overwrites the first clone(step) for each pipeline
predict_proba(X)[:, 1] with string labels the wrong class’s probability check est.classes_ first
sklearn.set_config(...) in a library changes every later estimator in the process config_context or set_output per estimator
joblib.load on a shared file arbitrary code can run trusted files only; skops with a reviewed list

Preprocessing turns raw columns into numbers a model can use, with parameters learned from the training rows only. This page covers scalers, encoders, imputers, binning, polynomial and date features, transforms for skewed values, feature selection and the rules that keep test data out of training. The examples use data/houses.csv and data/customers.csv. The blocks share one session:

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
houses = pd.read_csv("data/houses.csv")
customers = pd.read_csv("data/customers.csv")
h_train, h_test = train_test_split(houses, test_size=0.25, random_state=42)
c_train, c_test = train_test_split(
customers, test_size=0.25, stratify=customers["churned"], random_state=42
)
I want to… Use… Notes
mean 0, standard deviation 1 StandardScaler() linear models, SVM, KNN, PCA, neural nets
a fixed range such as 0–1 MinMaxScaler(feature_range=(0, 1), clip=True) bounded inputs, images
scaling that ignores outliers RobustScaler() median and IQR
scale sparse data MaxAbsScaler() keeps zeros
make a skewed column look normal PowerTransformer() (Yeo-Johnson) method="box-cox" for positive data
ranks to a uniform or normal shape QuantileTransformer(output_distribution="normal") robust to outliers; non-linear
tame a right tail by hand np.log1p(x); undo with np.expm1 counts, prices, durations
scale each row to length 1 Normalizer() text vectors, cosine similarity
one-hot encode, safe for new values OneHotEncoder(handle_unknown="ignore", sparse_output=False)
merge rare categories OneHotEncoder(min_frequency=20, handle_unknown="infrequent_if_exist") one infrequent_sklearn column
drop one dummy per feature OneHotEncoder(drop="first") unpenalized linear models
integers for ordered categories OrdinalEncoder(categories=[["basic", "standard", "premium"]]) default order is alphabetical
a code for unseen categories OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1) trees
encode a high-cardinality column TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=42)) cross-fitted
use categories natively category dtype + HistGradientBoosting*, LightGBM, XGBoost no encoding needed
fill blanks with the median SimpleImputer(strategy="median") "most_frequent", "constant"
fill blanks and keep a flag SimpleImputer(add_indicator=True) missingness can predict
fill from similar rows KNNImputer(n_neighbors=5) scale first
fill from the other columns IterativeImputer(random_state=42) from sklearn.experimental import enable_iterative_imputer
bins with fixed edges pd.cut(x, bins=[...], right=False) exploration, reports
bins learned in fit KBinsDiscretizer(n_bins=5, encode="ordinal") inside a pipeline
squares and products PolynomialFeatures(degree=2, include_bias=False)
products only PolynomialFeatures(interaction_only=True, include_bias=False)
smooth curves for linear models SplineTransformer(n_knots=5, degree=3)
a cycle (month, hour) sin(2πx/P) and cos(2πx/P), or SplineTransformer(extrapolation="periodic") always both columns
day of week s.dt.day_of_week Monday = 0
elapsed time (snapshot - s).dt.days a fixed snapshot date
drop constant columns VarianceThreshold(threshold=0.0)
keep the k best by a univariate test SelectKBest(f_classif, k=10) filter
rank by non-linear dependence mutual_info_classif(X, y, random_state=42) filter
drop features by model weights RFE(model, n_features_to_select=10), RFECV wrapper
add features greedily by CV score SequentialFeatureSelector(model, n_features_to_select=5) wrapper
keep features a model uses SelectFromModel(Lasso(alpha=0.01)) embedded
keep column names in outputs set_output(transform="pandas") before fit
evaluate without leakage every learned step in a Pipeline then cross_val_score
Scaler Formula Use when Outliers Key options
StandardScaler (x−μ)/σ(x - \mu) / \sigma the default for scale-sensitive models pulled by them with_mean=False for sparse
MinMaxScaler (x−min⁡)/(max⁡−min⁡)(x - \min) / (\max - \min) a bounded range is required very sensitive feature_range, clip=True
RobustScaler (x−median)/IQR(x - \text{median}) / \text{IQR} outliers you want to keep robust quantile_range=(25.0, 75.0)
MaxAbsScaler x/max⁡∣x∣x / \max \lvert x \rvert sparse data sensitive
PowerTransformer Yeo-Johnson or Box-Cox, then standardize skewed columns for linear models reduced method, standardize=True
QuantileTransformer empirical CDF, then uniform or normal heavy tails, odd shapes robust n_quantiles, output_distribution
Normalizer each row divided by its norm rows are vectors (text, counts) — norm="l2"
Model Needs scaling?
KNN, k-means, SVM, PCA, neural networks yes: distances and gradients follow the largest unit
Ridge, Lasso, ElasticNet, LogisticRegression (penalized by default) yes: the penalty treats all weights alike
LinearRegression no for predictions; yes to compare coefficients
trees, forests, gradient boosting, HistGradientBoosting* no: splits depend only on the order of values
from sklearn.preprocessing import (
PowerTransformer,
QuantileTransformer,
RobustScaler,
StandardScaler,
)
lot = h_train[["lot_sqft"]].dropna() # right-skewed, a few huge lots
print(f"raw skew {lot['lot_sqft'].skew():.2f}")
for step in [StandardScaler(), RobustScaler(), PowerTransformer(),
QuantileTransformer(output_distribution="normal", random_state=42)]:
z = step.set_output(transform="pandas").fit_transform(lot)["lot_sqft"]
print(f"{type(step).__name__:<20} skew {z.skew():6.2f} max {z.max():6.2f}")
Output
raw skew 1.13
StandardScaler skew 1.13 max 6.31
RobustScaler skew 1.13 max 4.90
PowerTransformer skew -0.03 max 3.46
QuantileTransformer skew -0.01 max 5.20

Linear scalers keep the shape, so the skew does not change. Only the power and quantile transforms change it.

Encoder Output Unknown categories Rare categories Use for
OneHotEncoder one 0/1 column per category handle_unknown="ignore": all zeros min_frequency, max_categories nominal columns, up to a few dozen levels
OrdinalEncoder one integer column handle_unknown="use_encoded_value", unknown_value=-1 min_frequency, max_categories ordered levels; trees
TargetEncoder one column (one per class for multiclass) the global target mean shrunk to the mean (smooth="auto") high cardinality: zip codes, product ids
category dtype the column itself NaN in the model — HistGradientBoosting*, LightGBM, XGBoost
pd.get_dummies dummy columns not remembered between calls — exploration only
handle_unknown= OneHotEncoder behavior
"error" (default) raises on a new category
"ignore" all zeros for that feature
"infrequent_if_exist" maps it to the infrequent column (with min_frequency or max_categories)
"warn" like "infrequent_if_exist" and warns
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder
train_hood = h_train[["neighborhood"]]
new = pd.DataFrame({"neighborhood": ["Westfield", "Harbor Point"]}) # one unseen
ohe = OneHotEncoder(min_frequency=300, handle_unknown="infrequent_if_exist",
sparse_output=False).fit(train_hood)
print(ohe.get_feature_names_out())
print(ohe.transform(new)) # Harbor Point -> the infrequent column
plan = OrdinalEncoder(categories=[["basic", "standard", "premium"]],
handle_unknown="use_encoded_value", unknown_value=-1)
print(plan.fit_transform(c_train[["plan"]].head(4)).ravel(),
c_train["plan"].head(4).tolist())
Output
['neighborhood_Cedar Park' 'neighborhood_Maple Grove'
'neighborhood_Westfield' 'neighborhood_infrequent_sklearn']
[[0. 0. 1. 0.]
[0. 0. 0. 1.]]
[0. 1. 0. 0.] ['basic', 'standard', 'basic', 'basic']

Target encoding replaces each category by a shrunken mean of the target. Shrinkage mm pulls small categories toward the global mean yˉ\bar{y}:

enc(c)=nc yˉc+m yˉnc+m\text{enc}(c) = \frac{n_c\,\bar{y}_c + m\,\bar{y}}{n_c + m}

This holds for a number passed as smooth=m. The default smooth="auto" estimates the shrinkage per category from the target variance (empirical Bayes).

from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import TargetEncoder
te = TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=42))
X_pay, y_pay = c_train[["payment_method"]], c_train["churned"]
cross_fitted = te.fit_transform(X_pay, y_pay) # each row: from the other 4 folds
naive = te.transform(X_pay) # every row: from all rows, its own target included
print(pd.Series(te.encodings_[0], index=te.categories_[0]).round(3).to_dict())
print(cross_fitted[:3].ravel().round(3), naive[:3].ravel().round(3))
Output
{'bank_transfer': 0.183, 'credit_card': 0.152, 'electronic_check': 0.246, 'paypal': 0.171}
[0.249 0.174 0.153] [0.246 0.171 0.152]
Target encoding rule Why
fit_transform(X_train, y_train) for training rows cross-fitting: no row sees its own target
transform(X_test) for new rows uses the means from all training rows
never fit(X, y).transform(X) on the training rows that is naive target encoding and leaks
pass a splitter to cv= shuffle= and random_state= are deprecated in scikit-learn 1.9
target_type="auto" binary, multiclass (one column per class) or continuous
Tool Fills with Notes
SimpleImputer(strategy="mean") column mean the default
SimpleImputer(strategy="median") column median skewed columns
SimpleImputer(strategy="most_frequent") the mode categories and numbers
SimpleImputer(strategy="constant", fill_value="missing") a fixed value an explicit “missing” category
add_indicator=True (any imputer) adds missingindicator_<col> columns when missingness itself predicts
KNNImputer(n_neighbors=5, weights="distance") mean of the nearest rows scale first; slow on big data
IterativeImputer(random_state=42, max_iter=10) a model of each column on the others experimental import; can warn about convergence
MissingIndicator() the flags only
native NaN support — trees, forests, HistGradientBoosting*, XGBoost, LightGBM
from sklearn.impute import KNNImputer, SimpleImputer
cols = ["lot_sqft", "school_rating"]
print(h_train[cols].isna().sum().to_dict())
median = SimpleImputer(strategy="median", add_indicator=True)
median.set_output(transform="pandas")
print(median.fit_transform(h_train[cols]).columns.tolist())
print(median.statistics_.tolist()) # learned on the training rows
knn = KNNImputer(n_neighbors=5).set_output(transform="pandas")
filled = knn.fit_transform(h_train[["sqft", "lot_sqft"]])
print(filled["lot_sqft"].isna().sum(), filled.shape)
Output
{'lot_sqft': 71, 'school_rating': 70}
['lot_sqft', 'school_rating', 'missingindicator_lot_sqft', 'missingindicator_school_rating']
[7590.0, 6.0]
0 (2250, 2)
Tool Edges Notes
pd.cut(x, bins=[18, 30, 45, 60, 120], right=False) yours [a, b) intervals; labels with labels=
pd.qcut(x, q=4, retbins=True) quantiles of x keep the edges to bin new data
KBinsDiscretizer(n_bins, encode, strategy) learned in fit strategy: "quantile" (default), "uniform", "kmeans"
encode= "onehot" (sparse, default), "onehot-dense", "ordinal"
from sklearn.preprocessing import KBinsDiscretizer
binner = KBinsDiscretizer(n_bins=4, encode="ordinal", strategy="quantile")
binner.fit(h_train[["sqft"]])
print(binner.bin_edges_[0]) # learned quartile edges
print(binner.transform(h_test[["sqft"]][:4]).ravel(), h_test["sqft"][:4].tolist())
age_band = pd.cut(customers["age"], bins=[18, 30, 45, 60, 120], right=False)
print(age_band.astype(str).value_counts(sort=False).to_dict())
Output
[ 550. 1360. 1745. 2210. 5710.]
[1. 0. 3. 2.] [1400, 1340, 2820, 2150]
{'[18, 30)': 842, '[30, 45)': 1994, '[45, 60)': 1703, '[60, 120)': 461}

Polynomial, interaction and spline features

Section titled “Polynomial, interaction and spline features”
Tool Adds Notes
PolynomialFeatures(degree=2, include_bias=False) squares and pairwise products nn features → (n+dd)−1\binom{n+d}{d} - 1 columns
PolynomialFeatures(interaction_only=True, include_bias=False) products only no squares
SplineTransformer(n_knots=5, degree=3) smooth piecewise curves per feature better behaved than high powers
SplineTransformer(extrapolation="periodic") a curve that wraps around cycles: hour, month
df["a"] * df["b"] one chosen interaction cheap and readable
nn features degree 2 degree 3 degree 2, interactions only
5 20 55 15
10 65 285 55
20 230 1,770 210
from sklearn.preprocessing import PolynomialFeatures, SplineTransformer
two = h_train[["sqft", "year_built"]].head(2)
poly = PolynomialFeatures(degree=2, include_bias=False).set_output(transform="pandas")
print(poly.fit_transform(two).columns.tolist())
spline = SplineTransformer(n_knots=4, degree=3).fit(h_train[["sqft"]])
print(spline.n_features_out_, spline.get_feature_names_out()[:3])
Output
['sqft', 'year_built', 'sqft^2', 'sqft year_built', 'year_built^2']
6 ['sqft_sp_0' 'sqft_sp_1' 'sqft_sp_2']
Feature pandas Notes
year, month, day, hour s.dt.year, s.dt.month, s.dt.day, s.dt.hour
day of week s.dt.day_of_week Monday = 0; dt.weekday and dt.dayofweek warn in pandas 3
day of year s.dt.day_of_year
quarter, ISO week s.dt.quarter, s.dt.isocalendar().week
weekend flag s.dt.day_of_week >= 5
month start or end s.dt.is_month_start, s.dt.is_month_end
elapsed days (pd.Timestamp("2024-12-31") - s).dt.days a fixed snapshot date, never “today”
cyclical pair sin⁡(2πx/P)\sin(2\pi x / P), cos⁡(2πx/P)\cos(2\pi x / P) PP = 12 months, 7 days, 24 hours
sold = pd.to_datetime(houses["sold_date"].iloc[[0, 700, 1400]])
dates = pd.DataFrame({
"sold": sold.dt.date,
"dow": sold.dt.day_of_week,
"month": sold.dt.month,
"age_days": (pd.Timestamp("2024-12-31") - sold).dt.days,
"m_sin": np.sin(2 * np.pi * (sold.dt.month - 1) / 12).round(3),
"m_cos": np.cos(2 * np.pi * (sold.dt.month - 1) / 12).round(3),
})
print(dates)
Output
sold dow month age_days m_sin m_cos
0 2022-01-03 0 1 1093 0.000 1.000
700 2022-09-22 3 9 831 -0.866 -0.500
1400 2023-06-17 5 6 563 0.500 -0.866

With one sine column, February and June both get 0.5. The cosine column tells them apart, so always add both.

Transform Code Domain Inverse
log np.log(x) x>0x > 0 np.exp
log1p np.log1p(x) x≥0x \ge 0 (zeros allowed) np.expm1
square root np.sqrt(x) x≥0x \ge 0 x ** 2
Box-Cox PowerTransformer(method="box-cox") x>0x > 0 inverse_transform
Yeo-Johnson PowerTransformer() any real xx inverse_transform
quantile QuantileTransformer(output_distribution="normal") any inverse_transform
in a pipeline FunctionTransformer(np.log1p, inverse_func=np.expm1)
on the target TransformedTargetRegressor(regressor, func=np.log, inverse_func=np.exp) y>0y > 0 automatic

A model fitted on log⁡y\log y predicts the median, not the mean: np.exp of the prediction is a little below the mean in the original units.

Family Tool Scores features by Cost Watch out
filter VarianceThreshold(threshold) variance tiny depends on units
filter SelectKBest(f_classif, k), f_regression ANOVA F, linear correlation tiny one feature at a time; linear
filter SelectKBest(mutual_info_classif, k), mutual_info_regression mutual information small noisy; set random_state
filter chi2 chi-squared tiny non-negative features only
filter SelectPercentile, SelectFpr, SelectFdr the same tests tiny other cut-offs
wrapper RFE(estimator, n_features_to_select, step) refits, dropping the weakest medium needs coef_ or feature_importances_
wrapper RFECV(estimator, cv=5, scoring=...) RFE with CV to choose the count high n_features_ holds the count
wrapper SequentialFeatureSelector(est, direction="forward", cv=5) CV score of each addition high many fits
embedded Lasso(alpha), LogisticRegression(l1_ratio=1, solver="liblinear") L1 weights (zero = dropped) small scale first; picks one of correlated twins
embedded tree feature_importances_ impurity decrease small favors continuous, high-cardinality features
embedded SelectFromModel(estimator, threshold="median", max_features=...) any model’s weights or importances small wrap it in the pipeline
model-agnostic permutation_importance(model, X_val, y_val) score drop when a column is shuffled medium on validation data
from functools import partial
from sklearn.feature_selection import (
SelectFromModel,
SelectKBest,
mutual_info_regression,
)
from sklearn.linear_model import LassoCV
from sklearn.pipeline import make_pipeline
num = ["sqft", "bedrooms", "bathrooms", "year_built", "garage_spaces", "has_pool",
"condition", "distance_to_center_km"]
Xh, yh = h_train[num], np.log(h_train["price"])
kbest = SelectKBest(partial(mutual_info_regression, random_state=42), k=4)
print(kbest.fit(Xh, yh).get_feature_names_out())
lasso = make_pipeline(
StandardScaler(), # L1 weights are comparable only on one scale
SelectFromModel(LassoCV(cv=5, random_state=42), threshold="median"), # top half
)
print(lasso.fit(Xh, yh)[-1].get_feature_names_out(num))
Output
['sqft' 'bedrooms' 'bathrooms' 'distance_to_center_km']
['sqft' 'year_built' 'condition' 'distance_to_center_km']
  1. Split first. Compute every statistic (mean, category list, bin edge, selected feature) on the training rows only.
  2. Put every learned step inside the pipeline that you pass to cross_val_score or a search.
  3. For each feature, ask: “Is this value known at prediction time?”
  4. Drop ids, row numbers and anything computed from the target or from events after the prediction date.
  5. Split by group when an entity has several rows (GroupKFold); split by time for time-ordered data (TimeSeriesSplit).
  6. Lag before you roll: s.shift(1).rolling(7).mean(), never rolling(7, center=True).
  7. A score far above the baseline is a bug until proven otherwise. Score the top features one at a time.
Leak Example Fix
preprocessing on all rows StandardScaler().fit(X) before the split fit inside the pipeline
selection on all rows SelectKBest().fit(X, y) before CV the selector inside the pipeline
naive target encoding df.groupby(cat)[y].transform("mean") TargetEncoder.fit_transform
target leakage price_per_sqft to predict price drop the column
post-outcome data a “cancellation reason” to predict churn only data from before the prediction date
duplicates across the split the same house listed twice deduplicate first or split by group
the future in features centered windows, bfill, full-series scaling trailing windows; fit on the past only
Trap Symptom Fix
fit_transform on the test set test data scaled by its own statistics transform
StandardScaler vs pandas .std() small mismatches scikit-learn uses ddof=0, pandas ddof=1
MinMaxScaler on new extremes values outside 0–1 clip=True if the model needs the range
OrdinalEncoder() on ordered levels the order is alphabetical: basic, premium, standard pass categories=[[...]]
OneHotEncoder() on a new category ValueError: Found unknown categories handle_unknown="ignore"
OneHotEncoder() output a sparse matrix sparse_output=False (the old sparse= was removed)
TargetEncoder.fit(X, y).transform(X) optimistic training scores fit_transform cross-fits
TargetEncoder(shuffle=True, random_state=42) FutureWarning in scikit-learn 1.9 cv=StratifiedKFold(5, shuffle=True, random_state=42)
pd.get_dummies on train and test separately different columns OneHotEncoder
duplicate column names scikit-learn raises add_prefix before concat
np.log(0) -inf and a RuntimeWarning np.log1p; report errors after the inverse
one sine column for a cycle two months share one value add the cosine
KBinsDiscretizer(strategy="uniform") on a skewed column most bins almost empty "quantile"
PolynomialFeatures(degree=3) on many columns thousands of columns, slow, overfits chosen columns only, or splines
include_bias=True (default) a constant column next to the model’s intercept include_bias=False
VarianceThreshold on raw columns keeps sqft, drops a useful flag scale first or use it only for constants
impurity importances random ids rank high permutation importance on validation data
make_column_selector(dtype_include=object) Pandas4Warning dtype_include="str"
KNNImputer on unscaled columns neighbors chosen by the largest unit scale before imputing

Which model to try, what to tune first and what each one needs from preprocessing. This page has one table per task, a fast comparison loop, and the ensemble methods: bagging, random forests, boosting, voting and stacking. The examples use the bundled breast cancer and diabetes datasets, so they run in seconds. The blocks share one session:

import numpy as np
from sklearn.datasets import load_breast_cancer, load_diabetes
from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from threadpoolctl import threadpool_limits
threadpool_limits(limits=1) # one thread for OpenMP and BLAS: fast on small data
Xc, yc = load_breast_cancer(return_X_y=True, as_frame=True) # 569 rows, 30 features
Xr, yr = load_diabetes(return_X_y=True, as_frame=True) # 442 rows, 10 features
cv_c = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
cv_r = KFold(n_splits=5, shuffle=True, random_state=42)

threadpool_limits(limits=1) caps the threads of the libraries that boosting and linear algebra use. On tables this small, threads cost more than they save. Scores do not change.

I want to… Use… Notes
a floor for any regressor DummyRegressor(strategy="mean") R² ≈ 0
a floor for any classifier DummyClassifier(strategy="most_frequent") accuracy = majority share
a linear regression LinearRegression() no tuning; no penalty
shrink correlated weights Ridge(alpha=1.0), RidgeCV(alphas=np.logspace(-3, 3, 13)) scale first
zero out useless weights Lasso(alpha=...), LassoCV(cv=5) scale first
mix L1 and L2 ElasticNet(alpha, l1_ratio=0.5), ElasticNetCV
a regression robust to outliers HuberRegressor(epsilon=1.35)
predict a median or other quantile QuantileRegressor(quantile=0.9, alpha=0) slow on big data; HGB loss="quantile"
counts or positive skewed targets PoissonRegressor(), TweedieRegressor(power=1.5), GammaRegressor() log link
a first, explainable classifier LogisticRegression(max_iter=1000) after scaling odds ratios
no penalty in logistic regression LogisticRegression(C=np.inf) penalty= is deprecated in 1.9
an L1 logistic regression LogisticRegression(l1_ratio=1, solver="liblinear") or "saga" sparse weights
a linear model on millions of rows SGDClassifier(loss="log_loss"), SGDRegressor() scale; partial_fit for streams
a linear SVM LinearSVC(C=1.0) no probabilities
a kernel SVM SVC(kernel="rbf", C=1, gamma="scale"), SVR small or medium data
similar rows vote KNeighborsClassifier(n_neighbors=5), KNeighborsRegressor scale first
a baseline for text counts MultinomialNB(), ComplementNB()
readable rules DecisionTreeClassifier(max_depth=4) sklearn.tree.export_text
a strong default with little tuning RandomForestClassifier(n_estimators=300, n_jobs=-1) oob_score=True
more randomness, faster forests ExtraTreesClassifier(), ExtraTreesRegressor() random split points
the best tabular accuracy HistGradientBoostingClassifier(), XGBoost, LightGBM see boosting
a small neural network MLPClassifier(hidden_layer_sizes=(64,), early_stopping=True) scale; PyTorch for more
bag any model BaggingClassifier(estimator, n_estimators=50, oob_score=True) variance down
boost stumps AdaBoostClassifier(n_estimators=100) the classic
average different models VotingClassifier(models, voting="soft") needs predict_proba
learn how to combine models StackingClassifier(models, final_estimator=LogisticRegression(), cv=5) out-of-fold
monotonic effects monotonic_cst=[1, 0, -1] on trees, forests and HGB business rules
one model per class pair OneVsOneClassifier(model), OneVsRestClassifier(model) multiclass from binary
several targets at once MultiOutputRegressor(model), RegressorChain(model)
list every estimator sklearn.utils.all_estimators(type_filter="classifier")
Class Key hyperparameters Scale? NaN Categories Notes
LinearRegression — for coefficients only no one-hot closed form; extrapolates linearly
Ridge, RidgeCV alpha yes no one-hot L2; never zero weights; fast
Lasso, LassoCV alpha yes no one-hot L1; selects features
ElasticNet, ElasticNetCV alpha, l1_ratio yes no one-hot correlated groups kept together
HuberRegressor epsilon, alpha yes no one-hot squared loss near 0, linear in the tails
QuantileRegressor quantile, alpha yes no one-hot linear quantiles; slow above ~10k rows
PoissonRegressor, GammaRegressor, TweedieRegressor alpha, power yes no one-hot GLMs for counts, costs, claims
SGDRegressor alpha, penalty, learning_rate yes no one-hot huge data; partial_fit
KNeighborsRegressor n_neighbors, weights yes no one-hot no training; never extrapolates
SVR C, epsilon, gamma yes no one-hot slow above ~20k rows
DecisionTreeRegressor max_depth, min_samples_leaf, ccp_alpha no yes ordinal or one-hot step function; unstable
RandomForestRegressor n_estimators, max_features, min_samples_leaf no yes ordinal or one-hot default max_features=1.0 is bagging; try 0.3–0.6
ExtraTreesRegressor as random forest no yes ordinal or one-hot no bootstrap by default
GradientBoostingRegressor learning_rate, n_estimators, max_depth, subsample no no ordinal or one-hot slow; small data only
HistGradientBoostingRegressor learning_rate, max_iter, max_leaf_nodes, l2_regularization no yes native (category dtype) fast; loss="poisson", "quantile"
xgboost.XGBRegressor n_estimators, learning_rate, max_depth, subsample no yes native see boosting
lightgbm.LGBMRegressor n_estimators, learning_rate, num_leaves, min_child_samples no yes native verbose=-1
MLPRegressor hidden_layer_sizes, alpha, learning_rate_init yes no one-hot needs many rows and tuning
Class Key hyperparameters Scale? NaN Categories Probabilities Notes
LogisticRegression C, l1_ratio, class_weight yes no one-hot yes, usually calibrated odds ratios; C smaller = stronger penalty
SGDClassifier loss, alpha, penalty yes no one-hot with loss="log_loss" big or streaming data
RidgeClassifier alpha yes no one-hot no fast multiclass linear baseline
LinearSVC C yes no one-hot no (decision_function) text, many features
SVC C, kernel, gamma yes no one-hot no; CalibratedClassifierCV probability= is deprecated in 1.9
KNeighborsClassifier n_neighbors, weights, metric yes no one-hot steps of 1/k slow predictions on big data
GaussianNB var_smoothing no no no poorly calibrated instant baseline
MultinomialNB, ComplementNB alpha no no counts poorly calibrated text counts
LinearDiscriminantAnalysis solver, shrinkage no no one-hot yes also a supervised projection
DecisionTreeClassifier max_depth, min_samples_leaf, ccp_alpha no yes ordinal or one-hot leaf shares readable; overfits alone
RandomForestClassifier n_estimators, max_features ("sqrt"), min_samples_leaf no yes ordinal or one-hot yes strong default
ExtraTreesClassifier as random forest no yes ordinal or one-hot yes faster, smoother
GradientBoostingClassifier learning_rate, n_estimators, max_depth no no ordinal or one-hot yes small data only
HistGradientBoostingClassifier learning_rate, max_iter, max_leaf_nodes, class_weight no yes native yes fast, strong default
xgboost.XGBClassifier n_estimators, learning_rate, max_depth, scale_pos_weight no yes native yes GPU support
lightgbm.LGBMClassifier n_estimators, learning_rate, num_leaves, class_weight no yes native yes very fast on big data
MLPClassifier hidden_layer_sizes, alpha, early_stopping yes no one-hot yes PyTorch for real deep learning

“NaN: yes” means the model accepts missing values in X (in scikit-learn 1.9: trees, random forests, extra trees, bagging and HGB; also XGBoost and LightGBM). Every other model needs an imputer in the pipeline. “Native” categories means a pandas category column, without encoding.

Every model gets the same folds. Scale-sensitive models carry their scaler in a pipeline:

from sklearn.dummy import DummyClassifier
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
classifiers = {
"dummy": DummyClassifier(strategy="prior"),
"logreg": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
"knn": make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15)),
"svc": make_pipeline(StandardScaler(), SVC()), # ranks with decision_function
"nb": GaussianNB(),
"tree": DecisionTreeClassifier(max_depth=4, random_state=42),
"forest": RandomForestClassifier(n_estimators=200, random_state=42),
"hgb": HistGradientBoostingClassifier(random_state=42),
}
for name, model in classifiers.items():
auc = cross_val_score(model, Xc, yc, cv=cv_c, scoring="roc_auc")
print(f"{name:<7} ROC-AUC {auc.mean():.3f} ± {auc.std():.3f}")
Output
dummy ROC-AUC 0.500 ± 0.000
logreg ROC-AUC 0.995 ± 0.005
knn ROC-AUC 0.991 ± 0.008
svc ROC-AUC 0.995 ± 0.006
nb ROC-AUC 0.989 ± 0.006
tree ROC-AUC 0.915 ± 0.037
forest ROC-AUC 0.990 ± 0.008
hgb ROC-AUC 0.992 ± 0.006

This dataset is easy: every model except the dummy and the single tree scores above 0.98, and the gaps are smaller than one standard deviation. The single tree is the least stable model (the largest ± value).

from sklearn.dummy import DummyRegressor
from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressor
from sklearn.linear_model import HuberRegressor, LassoCV, RidgeCV
from sklearn.neighbors import KNeighborsRegressor
regressors = {
"dummy": DummyRegressor(),
"ridge": make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 3, 13))),
"lasso": make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=42)),
"huber": make_pipeline(StandardScaler(), HuberRegressor(max_iter=1000)),
"knn": make_pipeline(StandardScaler(), KNeighborsRegressor(n_neighbors=15)),
"forest": RandomForestRegressor(n_estimators=200, max_features=0.5,
min_samples_leaf=5, random_state=42),
"hgb": HistGradientBoostingRegressor(max_iter=100, learning_rate=0.05,
random_state=42),
}
for name, model in regressors.items():
r2 = cross_val_score(model, Xr, yr, cv=cv_r, scoring="r2")
print(f"{name:<6} R² {r2.mean():.3f} ± {r2.std():.3f}")
Output
dummy R² -0.019 ± 0.014
ridge R² 0.477 ± 0.083
lasso R² 0.474 ± 0.086
huber R² 0.476 ± 0.079
knn R² 0.433 ± 0.041
forest R² 0.455 ± 0.081
hgb R² 0.433 ± 0.082

On 442 rows of mostly linear signal, Ridge beats the forest and boosting. Tree ensembles usually pull ahead on larger tables with interactions and non-linear effects. Always run the linear baseline.

Situation First choice Then try
any new tabular problem dummy baseline + HistGradientBoosting* linear model for comparison
coefficients must be explained LogisticRegression, Ridge, a GLM add splines or interactions
a few hundred rows regularized linear model, small forest SVM with tuned C and gamma
millions of rows LightGBM, HistGradientBoosting*, SGD* XGBoost on GPU
thousands of sparse features (text) LogisticRegression, LinearSVC, ComplementNB SGDClassifier
many missing values HGB, XGBoost, LightGBM, trees and forests imputer + indicator for the others
high-cardinality categories HGB, LightGBM, XGBoost with native categories TargetEncoder for linear models
counts or skewed positive targets PoissonRegressor, HGB loss="poisson" log target
an interval, not a point HGB or LightGBM with loss="quantile" QuantileRegressor
images, audio, long text neural networks (PyTorch) pretrained models
Hyperparameter More flexible (variance up) Simpler (bias up)
C (logistic, SVM) larger smaller
alpha (Ridge, Lasso, GLMs, MLP) smaller larger
n_neighbors smaller larger
max_depth, max_leaf_nodes, num_leaves larger smaller
min_samples_leaf, min_child_samples smaller larger
gamma (RBF SVM) larger smaller
learning_rate × rounds (boosting) larger smaller
Method Base models Built Combined by Reduces scikit-learn
bagging one model on bootstrap samples in parallel mean or vote variance BaggingClassifier, BaggingRegressor
random forest deep trees, bootstrap + random features per split in parallel mean of probabilities variance RandomForest*
extra trees deep trees, random split thresholds in parallel mean variance ExtraTrees*
AdaBoost stumps on reweighted rows in sequence weighted vote bias AdaBoost*
gradient boosting small trees on the gradient of the loss in sequence sum of trees × learning rate bias GradientBoosting*, HistGradientBoosting*
voting different models in parallel mean of labels or probabilities variance (if diverse) VotingClassifier, VotingRegressor
stacking different models in parallel + a meta-model learned weights on out-of-fold predictions both (if diverse) StackingClassifier, StackingRegressor

Averaging MM models with error variance σ2\sigma^2 and error correlation ρ\rho leaves a variance of

Var⁡(eˉ)=ρ σ2+1−ρM σ2\operatorname{Var}(\bar{e}) = \rho\,\sigma^2 + \frac{1 - \rho}{M}\,\sigma^2

More models shrink only the second term. Only more diverse models (lower ρ\rho) shrink the first.

Parameter Bagging / forest Effect
n_estimators 100–500 more is never worse, only slower
max_features forest: "sqrt" (classifier), 1.0 (regressor) lower = more diverse trees
max_samples None = n rows smaller = faster, more diverse
min_samples_leaf 1 larger = smoother, smaller files
oob_score=True — a free validation score from the out-of-bag rows (~36.8%)
warm_start=True — add trees to a fitted forest
n_jobs=-1 — trees in parallel
from sklearn.ensemble import (
AdaBoostClassifier,
BaggingClassifier,
ExtraTreesClassifier,
StackingClassifier,
VotingClassifier,
)
forest = RandomForestClassifier(n_estimators=200, oob_score=True, random_state=42)
print(f"forest OOB accuracy {forest.fit(Xc, yc).oob_score_:.3f}") # no CV needed
ensembles = {
"bagged tree": BaggingClassifier(DecisionTreeClassifier(), n_estimators=100,
random_state=42),
"extra trees": ExtraTreesClassifier(n_estimators=200, random_state=42),
"adaboost": AdaBoostClassifier(n_estimators=100, random_state=42),
}
for name, model in ensembles.items():
auc = cross_val_score(model, Xc, yc, cv=cv_c, scoring="roc_auc").mean()
print(f"{name:<11} ROC-AUC {auc:.3f}")
Output
forest OOB accuracy 0.960
bagged tree ROC-AUC 0.988
extra trees ROC-AUC 0.994
adaboost ROC-AUC 0.993
Hard voting Soft voting Stacking
combines labels probabilities out-of-fold predictions
weights fixed (weights=) fixed (weights=) learned by final_estimator
predict_proba no yes yes
extra fits none none cv per base model, plus one refit each
key options voting="hard" voting="soft", weights cv, stack_method, passthrough=True (add raw features)
members = [
("logreg", classifiers["logreg"]),
("knn", classifiers["knn"]),
("forest", RandomForestClassifier(n_estimators=200, random_state=42)),
]
soft = VotingClassifier(members, voting="soft")
stack = StackingClassifier(members, final_estimator=LogisticRegression(), cv=cv_c)
for name, model in [("soft voting", soft), ("stacking", stack)]:
auc = cross_val_score(model, Xc, yc, cv=cv_c, scoring="roc_auc")
print(f"{name:<11} ROC-AUC {auc.mean():.3f} ± {auc.std():.3f}")
print("meta weights:", stack.fit(Xc, yc).final_estimator_.coef_.round(2))
Output
soft voting ROC-AUC 0.996 ± 0.005
stacking ROC-AUC 0.996 ± 0.005
meta weights: [[3.94 2.6 2.45]]

An ensemble earns its cost only when the gain beats the fold-to-fold noise and the members disagree. Two models whose predictions correlate at 0.95 or more add little.

Trap Symptom Fix
no scaling before KNN, SVM, penalized linear models, MLP the largest-unit column dominates; weak scores StandardScaler in the pipeline
LogisticRegression(penalty="l1") FutureWarning in scikit-learn 1.9 l1_ratio=1 with solver="liblinear" or "saga"; C=np.inf for no penalty
SVC(probability=True) deprecated in 1.9, slow, can contradict predict decision_function, or CalibratedClassifierCV(SVC(), ensemble=False)
ConvergenceWarning from a linear model or MLP unscaled data or too few iterations scale; raise max_iter
RandomForestRegressor() defaults max_features=1.0: bagging, correlated trees max_features 0.3–0.6
an unlimited DecisionTree* training score 1.0, weak validation score max_depth, min_samples_leaf or ccp_alpha
trees, forests, KNN outside the training range flat predictions at the edge linear terms, a log or ratio target
GaussianNB probabilities almost always 0 or 1 use it for ranking, or calibrate
GradientBoosting* on large data very slow HistGradientBoosting*
hard voting no predict_proba, so no ROC-AUC or threshold voting="soft"
stacking on in-sample predictions the meta-model trusts the most overfit member StackingClassifier with cv (the default does it)
criterion="friedman_mse" deprecated in scikit-learn 1.9 leave the default
comparing models on different folds differences come from the split, not the model one splitter object for every model
a small CV gain noise read as signal compare the paired fold scores; keep the simpler model

A metric turns predictions into one number that you can compare. This page gives the formula, the scikit-learn function and the scoring= name of each common metric, for regression, classification, probabilities, ranking and forecasts, and then shows how to choose a decision threshold. The examples use data/houses.csv, data/customers.csv and data/web_traffic.csv. The blocks share one session:

import numpy as np
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from threadpoolctl import threadpool_limits
threadpool_limits(limits=1) # one thread: faster on small data, same scores
houses = pd.read_csv("data/houses.csv").astype({"neighborhood": "category"})
Xh = houses.drop(columns=["house_id", "sold_date", "price"])
Xh_tr, Xh_te, yh_tr, yh_te = train_test_split(
Xh, houses["price"], test_size=0.25, random_state=42
)
reg = HistGradientBoostingRegressor(random_state=42).fit(Xh_tr, yh_tr)
pred_h = reg.predict(Xh_te) # USD
customers = pd.read_csv("data/customers.csv")
Xc = customers[["tenure_months", "monthly_charges", "support_tickets", "contract"]]
Xc_tr, Xc_te, yc_tr, yc_te = train_test_split(
Xc, customers["churned"], test_size=0.25, stratify=customers["churned"],
random_state=42,
)
prep = make_column_transformer(
(OneHotEncoder(handle_unknown="ignore"), ["contract"]), remainder=StandardScaler()
)
clf = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(Xc_tr, yc_tr)
proba = clf.predict_proba(Xc_te)[:, 1] # P(churn)
pred_c = clf.predict(Xc_te) # 1 when P(churn) > 0.5
print(f"churn rate {yc_te.mean():.3f}, test rows {len(yc_te)}")
Output
churn rate 0.193, test rows 1250
I want to… Use… scoring= name
the typical error in target units mean_absolute_error(y, p) "neg_mean_absolute_error"
an error that punishes big misses root_mean_squared_error(y, p) "neg_root_mean_squared_error"
the share of variance explained r2_score(y, p) "r2"
a relative error mean_absolute_percentage_error(y, p) "neg_mean_absolute_percentage_error"
an error robust to outliers median_absolute_error(y, p) "neg_median_absolute_error"
errors in ratios (log scale) root_mean_squared_log_error(y, p) "neg_root_mean_squared_log_error"
the quality of a quantile forecast mean_pinball_loss(y, p, alpha=0.9) make_scorer(..., greater_is_better=False)
count each kind of error confusion_matrix(y, pred).ravel() (TN, FP, FN, TP)
precision, recall, F1 per class classification_report(y, pred, digits=3)
the share of flagged rows that are right precision_score(y, pred) "precision"
the share of positives caught recall_score(y, pred) "recall"
one number for precision and recall f1_score(y, pred), fbeta_score(y, pred, beta=2) "f1"
accuracy that respects rare classes balanced_accuracy_score(y, pred) "balanced_accuracy"
one balanced number from the confusion matrix matthews_corrcoef(y, pred) "matthews_corrcoef"
a ranking quality, any threshold roc_auc_score(y, proba) "roc_auc"
ranking quality with rare positives average_precision_score(y, proba) "average_precision"
the quality of probabilities log_loss(y, proba), brier_score_loss(y, proba) "neg_log_loss", "neg_brier_score"
probabilities vs observed rates calibration_curve(y, proba, n_bins=10)
multiclass ROC-AUC roc_auc_score(y, P, multi_class="ovr") "roc_auc_ovr"
a macro average over classes f1_score(y, pred, average="macro") "f1_macro"
precision in the top k sort by score, take k, average y custom
a ranking metric with graded relevance ndcg_score(y_rel, scores, k=10)
every point of the precision–recall trade-off precision_recall_curve(y, proba)
a fixed threshold in a model FixedThresholdClassifier(model, threshold=0.3)
a threshold chosen by CV TunedThresholdClassifierCV(model, scoring="f1")
a scale-free forecast error MASE: MAE ÷ in-sample seasonal naive MAE custom
list every scorer name sklearn.metrics.get_scorer_names()
a scorer from my own function make_scorer(func, greater_is_better=False)

Every metric takes (y_true, y_pred) in that order.

Metric Formula Function Unit Misleads when
MAE 1n∑∣y−y^∣\frac{1}{n}\sum \lvert y - \hat{y} \rvert mean_absolute_error target large misses matter more than small ones
MSE 1n∑(y−y^)2\frac{1}{n}\sum (y - \hat{y})^2 mean_squared_error target² always hard to read
RMSE MSE\sqrt{\text{MSE}} root_mean_squared_error target a few outliers dominate
R² 1−∑(y−y^)2∑(y−yˉ)21 - \frac{\sum (y - \hat{y})^2}{\sum (y - \bar{y})^2} r2_score none, ≤ 1 comparing test sets with different spreads
MAPE 1n∑∣y−y^y∣\frac{1}{n}\sum \left\lvert \frac{y - \hat{y}}{y} \right\rvert mean_absolute_percentage_error fraction yy near 0; favors under-forecasts
MedAE median⁡∣y−y^∣\operatorname{median} \lvert y - \hat{y} \rvert median_absolute_error target hides the tail
max error max⁡∣y−y^∣\max \lvert y - \hat{y} \rvert max_error target one row decides
RMSLE 1n∑(log⁡(1+y)−log⁡(1+y^))2\sqrt{\frac{1}{n}\sum (\log(1+y) - \log(1+\hat{y}))^2} root_mean_squared_log_error log ratio needs y,y^>−1y, \hat{y} > -1
pinball loss 1n∑max⁡(α(y−y^), (α−1)(y−y^))\frac{1}{n}\sum \max(\alpha(y - \hat{y}),\,(\alpha - 1)(y - \hat{y})) mean_pinball_loss(alpha=) target used for a mean forecast
Poisson deviance 2n∑(ylog⁡yy^−y+y^)\frac{2}{n}\sum \left(y \log\frac{y}{\hat{y}} - y + \hat{y}\right) mean_poisson_deviance none y^≤0\hat{y} \le 0
D² (absolute error) 1−∑∣y−y^∣∑∣y−median⁡(y)∣1 - \frac{\sum \lvert y - \hat{y} \rvert}{\sum \lvert y - \operatorname{median}(y) \rvert} d2_absolute_error_score none, ≤ 1 as R², for MAE
from sklearn.metrics import (
max_error,
mean_absolute_error,
mean_absolute_percentage_error,
median_absolute_error,
r2_score,
root_mean_squared_error,
root_mean_squared_log_error,
)
print(f"MAE {mean_absolute_error(yh_te, pred_h):>9,.0f}") # y_true first
print(f"RMSE {root_mean_squared_error(yh_te, pred_h):>9,.0f}")
print(f"MedAE {median_absolute_error(yh_te, pred_h):>9,.0f}")
print(f"max {max_error(yh_te, pred_h):>9,.0f}")
print(f"R² {r2_score(yh_te, pred_h):>9.3f}")
print(f"MAPE {mean_absolute_percentage_error(yh_te, pred_h):>9.1%}") # a fraction
print(f"RMSLE {root_mean_squared_log_error(yh_te, pred_h):>9.3f}")
Output
MAE 60,889
RMSE 97,559
MedAE 39,804
max 737,561
R² 0.909
MAPE 12.5%
RMSLE 0.155

RMSE ≥ MAE always. A large gap means a few big misses: inspect the worst rows.

predicted 0 predicted 1
actual 0 (neg) TN FP specificity = TN / (TN + FP)
actual 1 (pos) FN TP recall = TP / (TP + FN)
precision = TP / (TP + FP)
Metric Formula Function Range Use when
accuracy TP+TNn\frac{TP + TN}{n} accuracy_score 0–1 balanced classes, equal costs
balanced accuracy mean recall over classes balanced_accuracy_score 1/K random (0.5 for binary) – 1 imbalanced classes
precision TPTP+FP\frac{TP}{TP + FP} precision_score 0–1 false alarms are expensive
recall (sensitivity, TPR) TPTP+FN\frac{TP}{TP + FN} recall_score 0–1 misses are expensive
specificity (TNR) TNTN+FP\frac{TN}{TN + FP} recall_score(y, pred, pos_label=0) 0–1 screening tests
F1 2PRP+R\frac{2PR}{P + R} f1_score 0–1 one number for P and R
F-beta (1+β2)PRβ2P+R\frac{(1 + \beta^2) P R}{\beta^2 P + R} fbeta_score(beta=2) 0–1 β>1\beta > 1 weighs recall more
MCC TP⋅TN−FP⋅FN(TP+FP)(TP+FN)(TN+FP)(TN+FN)\frac{TP \cdot TN - FP \cdot FN}{\sqrt{(TP+FP)(TP+FN)(TN+FP)(TN+FN)}} matthews_corrcoef −1 to 1 one honest number for imbalance
Cohen’s kappa po−pe1−pe\frac{p_o - p_e}{1 - p_e} cohen_kappa_score −1 to 1 agreement beyond chance (annotators)
from sklearn.metrics import (
accuracy_score,
balanced_accuracy_score,
classification_report,
confusion_matrix,
f1_score,
fbeta_score,
matthews_corrcoef,
precision_score,
recall_score,
)
tn, fp, fn, tp = confusion_matrix(yc_te, pred_c).ravel() # true labels first
print(f"TN {tn} FP {fp} FN {fn} TP {tp}")
print(f"accuracy {accuracy_score(yc_te, pred_c):.3f} "
f"balanced {balanced_accuracy_score(yc_te, pred_c):.3f} "
f"MCC {matthews_corrcoef(yc_te, pred_c):.3f}")
print(f"precision {precision_score(yc_te, pred_c):.3f} "
f"recall {recall_score(yc_te, pred_c):.3f} "
f"F1 {f1_score(yc_te, pred_c):.3f} F2 {fbeta_score(yc_te, pred_c, beta=2):.3f}")
print(classification_report(yc_te, pred_c, digits=3, target_names=["stay", "churn"]))
Output
TN 969 FP 40 FN 177 TP 64
accuracy 0.826 balanced 0.613 MCC 0.323
precision 0.615 recall 0.266 F1 0.371 F2 0.300
precision recall f1-score support
stay 0.846 0.960 0.899 1009
churn 0.615 0.266 0.371 241
accuracy 0.826 1250
macro avg 0.730 0.613 0.635 1250
weighted avg 0.801 0.826 0.797 1250

High accuracy with low recall: the model mostly predicts “stay”, like the majority baseline (accuracy 0.807 here).

average= Computes Use when
"binary" (default) the metric for pos_label=1 only two classes
"macro" plain mean over classes every class matters equally
"weighted" mean weighted by class size large classes matter more
"micro" pools TP, FP, FN over classes equals accuracy for single-label multiclass
None one value per class the honest view
Metric Formula Function Best Notes
log loss −1n∑[ylog⁡p+(1−y)log⁡(1−p)]-\frac{1}{n}\sum [y \log p + (1 - y)\log(1 - p)] log_loss 0 punishes confident mistakes hard
Brier score 1n∑(p−y)2\frac{1}{n}\sum (p - y)^2 brier_score_loss 0 MSE of the probabilities
D² log loss 1−log losslog loss of the base rate1 - \frac{\text{log loss}}{\text{log loss of the base rate}} d2_log_loss_score 1 like R² for probabilities
calibration curve observed rate per bin of pp calibration_curve(y, p, n_bins, strategy="quantile") the diagonal plot: CalibrationDisplay
from sklearn.calibration import calibration_curve
from sklearn.metrics import brier_score_loss, d2_log_loss_score, log_loss
base = np.full(len(yc_te), yc_tr.mean()) # always predict the training churn rate
for name, p in [("model", proba), ("base rate", base)]:
print(f"{name:<9} log loss {log_loss(yc_te, p):.3f} "
f"Brier {brier_score_loss(yc_te, p):.3f}")
print(f"D² log loss {d2_log_loss_score(yc_te, proba):.3f}")
observed, predicted = calibration_curve(yc_te, proba, n_bins=5, strategy="quantile")
print("predicted", predicted.round(2), "\nobserved ", observed.round(2))
Output
model log loss 0.396 Brier 0.124
base rate log loss 0.490 Brier 0.156
D² log loss 0.192
predicted [0.02 0.07 0.16 0.27 0.49]
observed [0.02 0.07 0.15 0.22 0.5 ]
Metric Meaning Function Random model
ROC-AUC P(a random positive scores above a random negative) roc_auc_score(y, score) 0.5
average precision (PR-AUC) mean precision over the recall levels average_precision_score(y, score) the positive share
precision at k positives among the top k y[np.argsort(-score)[:k]].mean() the positive share
lift at k precision at k ÷ positive share 1
top-k accuracy true class among the k highest scores top_k_accuracy_score(y, P, k=3) k / classes
NDCG at k discounted gain of graded relevance ndcg_score(y_rel, scores, k=10) depends
from sklearn.metrics import average_precision_score, roc_auc_score
y_arr = yc_te.to_numpy()
print(f"ROC-AUC {roc_auc_score(y_arr, proba):.3f} " # scores, never labels
f"AP {average_precision_score(y_arr, proba):.3f} base rate {y_arr.mean():.3f}")
order = np.argsort(-proba, kind="stable") # highest risk first
for k in [50, 125, 250]:
prec_k = y_arr[order[:k]].mean()
print(f"top {k:>3}: precision {prec_k:.3f}, lift {prec_k / y_arr.mean():.2f}")
Output
ROC-AUC 0.793 AP 0.533 base rate 0.193
top 50: precision 0.780, lift 4.05
top 125: precision 0.592, lift 3.07
top 250: precision 0.504, lift 2.61
Metric Formula Notes
MAE, RMSE as for regression in the units of the series
MAPE 100n∑∣yt−y^tyt∣\frac{100}{n}\sum \left\lvert \frac{y_t - \hat{y}_t}{y_t} \right\rvert breaks at 0; mean_absolute_percentage_error returns a fraction
sMAPE 100n∑2∣yt−y^t∣∣yt∣+∣y^t∣\frac{100}{n}\sum \frac{2 \lvert y_t - \hat{y}_t \rvert}{\lvert y_t \rvert + \lvert \hat{y}_t \rvert} 0–200 (some tools report a fraction, 0–2); not symmetric in practice
WAPE ∑∣yt−y^t∣∑∣yt∣\frac{\sum \lvert y_t - \hat{y}_t \rvert}{\sum \lvert y_t \rvert} total error ÷ total volume; robust to small values
MASE MAE1T−m∑t=m+1T∣yt−yt−m∣\frac{\text{MAE}}{\frac{1}{T - m}\sum_{t=m+1}^{T} \lvert y_t - y_{t-m} \rvert} below 1 beats the in-sample seasonal naive forecast
pinball loss as for regression, at each quantile quantile forecasts
interval coverage share of yty_t inside the interval 95% intervals should cover about 95%
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
units = sales.groupby("order_date")["quantity"].sum().asfreq("D", fill_value=0)
train, test = units.iloc[:-28], units.iloc[-28:] # the last 4 weeks are the test
forecast = np.tile(train.iloc[-7:].to_numpy(), 4) # seasonal naive: repeat last week
err = test.to_numpy() - forecast
hist = train.to_numpy()
scale = np.mean(np.abs(hist[7:] - hist[:-7])) # in-sample seasonal naive MAE
mae = np.mean(np.abs(err))
print(f"MAE {mae:,.1f} units per day")
print(f"MAPE {np.mean(np.abs(err / test.to_numpy())):.1%}")
print(f"sMAPE {np.mean(2 * np.abs(err) / (np.abs(test) + np.abs(forecast))):.1%}")
print(f"WAPE {np.abs(err).sum() / test.abs().sum():.1%}")
print(f"MASE {mae / scale:.2f}")
Output
MAE 64.8 units per day
MAPE 96.1%
sMAPE 59.3%
WAPE 85.8%
MASE 4.51

The last training week holds the Black Friday peak (November 29 to December 2), so the seasonal naive forecast repeats that peak four times: MASE 4.51 means 4.5 times the in-sample naive error. MAPE is the largest of the percentages because low days, such as 16 units on December 25, divide by small numbers. The time-series page compares these metrics across several baselines and a SARIMA model.

cross_val_score, cross_validate and every search take scoring=: a name, a callable scorer(estimator, X, y), or a list or dict of them. Higher is always better, so errors come negated.

Task Names
regression "r2", "neg_mean_absolute_error", "neg_root_mean_squared_error", "neg_mean_absolute_percentage_error", "neg_median_absolute_error", "neg_root_mean_squared_log_error", "neg_mean_poisson_deviance", "d2_absolute_error_score"
binary labels "accuracy", "balanced_accuracy", "precision", "recall", "f1", "matthews_corrcoef"
binary scores "roc_auc", "average_precision", "neg_log_loss", "neg_brier_score"
multiclass "f1_macro", "f1_weighted", "precision_macro", "recall_macro", "roc_auc_ovr", "roc_auc_ovo", "neg_log_loss"
clustering (with true labels) "adjusted_rand_score", "adjusted_mutual_info_score"
from sklearn.metrics import fbeta_score, get_scorer_names, make_scorer
from sklearn.model_selection import StratifiedKFold, cross_validate
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
f2 = make_scorer(fbeta_score, beta=2) # extra arguments go to the metric
res = cross_validate(clf, Xc_tr, yc_tr, cv=cv,
scoring={"auc": "roc_auc", "f2": f2, "ll": "neg_log_loss"})
for key in ["test_auc", "test_f2", "test_ll"]:
print(f"{key:<8} {res[key].mean():.3f}") # neg_log_loss is negative
print("neg_root_mean_squared_error" in get_scorer_names())
Output
test_auc 0.799
test_f2 0.275
test_ll -0.395
True
make_scorer argument Meaning
greater_is_better=False an error: the scorer negates it
response_method="predict" (default) the metric gets labels
response_method="predict_proba" the metric gets probabilities (positive column for binary)
response_method=("decision_function", "predict_proba") the first method the model has
**kwargs passed to the metric: beta=2, average="macro", pos_label=0

predict uses 0.5 for probabilities (0 for decision_function). The best threshold depends on the costs. Choose it on validation data or with cross-validation, never on the test set.

Goal Rule
calibrated probabilities, cost cFPc_{FP} per false alarm, cFNc_{FN} per miss flag when p>cFPcFP+cFNp > \frac{c_{FP}}{c_{FP} + c_{FN}}
a recall target the highest threshold whose validation recall ≥ the target
a precision target the lowest threshold whose validation precision ≥ the target
a fixed capacity of k actions the top k scores
any score or cost function TunedThresholdClassifierCV(model, scoring=...)
from sklearn.metrics import precision_recall_curve
from sklearn.model_selection import FixedThresholdClassifier, TunedThresholdClassifierCV
def profit(y_true, y_pred): # a kept customer is worth 200, an offer costs 40
tp = ((y_true == 1) & (y_pred == 1)).sum()
return 200 * 0.3 * tp - 40 * y_pred.sum() # 30% of offered churners stay
tuned = TunedThresholdClassifierCV(clf, scoring=make_scorer(profit), cv=cv)
tuned.fit(Xc_tr, yc_tr) # threshold chosen by CV on the training rows
fixed = FixedThresholdClassifier(clf, threshold=0.3).fit(Xc_tr, yc_tr)
print(f"tuned threshold {tuned.best_threshold_:.3f}")
for name, model in [("0.5", clf), ("0.3", fixed), ("tuned", tuned)]:
pred = model.predict(Xc_te)
print(f"{name:<5} flagged {pred.sum():>4} recall {recall_score(yc_te, pred):.3f}"
f" profit {profit(yc_te.to_numpy(), pred):>8,.0f}")
prec, rec, thr = precision_recall_curve(yc_tr, clf.predict_proba(Xc_tr)[:, 1])
print(f"highest threshold with recall >= 0.8: {thr[rec[:-1] >= 0.8].max():.3f}")
Output
tuned threshold 0.600
0.5 flagged 104 recall 0.266 profit -320
0.3 flagged 324 recall 0.593 profit -4,380
tuned flagged 47 recall 0.154 profit 340
highest threshold with recall >= 0.8: 0.178

An offer pays off when 60p>4060p > 40, so the break-even probability is 40/60=0.66740 / 60 = 0.667; cross-validation picks a threshold close to it. The last line uses training-set predictions only to show the API. In practice use out-of-fold predictions: cross_val_predict(clf, X, y, cv=cv, method="predict_proba").

Trap Symptom Fix
arguments swapped: metric(pred, y) wrong R²; precision and recall exchanged always (y_true, y_pred)
labels passed to roc_auc_score AUC of one threshold, usually lower pass predict_proba(X)[:, 1] or decision_function(X)
accuracy on imbalanced data 0.81 for “nobody churns” balanced accuracy, recall, AP; print the baseline
neg_ scorer values negative scores in reports flip the sign
mean_squared_error(..., squared=False) TypeError (removed in 1.6) root_mean_squared_error
MAPE printed as 0.12 read as 0.12% it is a fraction: format with :.1%
MAPE with zeros in y huge or infinite values MAE, WAPE or MASE
R² compared across test sets a model “improves” on an easier split compare on the same rows
precision with nothing flagged UndefinedMetricWarning, value 0 zero_division=0 on purpose
pos_label metrics for the wrong class (load_breast_cancer: 1 = benign) recode, or pass pos_label=
predict_proba column order the probability of the wrong class it follows model.classes_
multiclass AUC from one column ValueError pass the full (n, K) matrix with multi_class="ovr"
a threshold tuned on the test set an optimistic test score TunedThresholdClassifierCV or a validation split
TunedThresholdClassifierCV(scoring="recall") threshold near 0: everything flagged tune on F1, F-beta or a cost
log_loss(y, pred) with labels huge values pass probabilities
macro vs weighted averages weighted hides a weak rare class report macro and the per-class table

Cross-validation estimates how a whole modeling procedure performs on new data. Tuning repeats that estimate for many settings and keeps the best one. This page covers the splitters, the CV functions, learning and validation curves, the scikit-learn searches, Optuna, nested CV and imbalanced classes. The examples use data/customers.csv (churn). The blocks share one session:

import numpy as np
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from threadpoolctl import threadpool_limits
threadpool_limits(limits=1) # one thread for OpenMP and BLAS: fast on small data
customers = pd.read_csv("data/customers.csv")
CAT = ["region", "plan", "contract", "payment_method"]
NUM = ["age", "tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
X, y = customers[CAT + NUM], customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42 # the test set waits
)
prep = make_column_transformer(
(OneHotEncoder(handle_unknown="ignore"), CAT), (StandardScaler(), NUM)
)
pipe = Pipeline([("prep", prep), ("model", LogisticRegression(max_iter=1000))])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # reuse everywhere
I want to… Use… Notes
k folds for regression KFold(5, shuffle=True, random_state=42)
k folds with equal class shares StratifiedKFold(5, shuffle=True, random_state=42) classification
a steadier estimate on small data RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=42) 15 fits
keep each customer in one fold GroupKFold(5) + groups=ids
groups and a rare class StratifiedGroupKFold(5, shuffle=True, random_state=42)
one fold per store or site LeaveOneGroupOut() few large groups
train on the past, test on the future TimeSeriesSplit(n_splits=5, test_size=28, gap=0) rows sorted by time
a fixed validation set PredefinedSplit(test_fold) -1 = always train
one CV score cross_val_score(pipe, X, y, cv=cv, scoring="roc_auc") an array, one per fold
several metrics, times, train scores cross_validate(..., scoring=[...], return_train_score=True) a dict of arrays
the fitted fold models cross_validate(..., return_estimator=True) res["estimator"]
an out-of-fold prediction for every row cross_val_predict(pipe, X, y, cv=cv, method="predict_proba") stacking, thresholds, plots
pass fit arguments cross_validate(..., params={"model__sample_weight": w})
does more data help? learning_curve / LearningCurveDisplay.from_estimator
one hyperparameter’s effect validation_curve / ValidationCurveDisplay.from_estimator
every combination GridSearchCV(pipe, grid, cv=cv, scoring=...)
a fixed budget of random settings RandomizedSearchCV(pipe, dists, n_iter=30, random_state=42)
scale-free values (C, alpha, rates) scipy.stats.loguniform(1e-3, 1e2)
many candidates, cheap rounds first HalvingRandomSearchCV(pipe, dists, factor=3) experimental import
search over different models a list of grids that set the model step
skip a step in a search {"prep__scale": ["passthrough", StandardScaler()]}
several metrics, refit on one scoring={"auc": "roc_auc", "ap": "average_precision"}, refit="auc"
all results as a table pd.DataFrame(search.cv_results_)
Bayesian optimization optuna.create_study(sampler=TPESampler(seed=42)) set_verbosity(WARNING)
an honest score for a tuned model cross_val_score(GridSearchCV(...), X, y, cv=outer) nested CV
weight a rare class class_weight="balanced" no extra rows
oversample inside CV imblearn.pipeline.make_pipeline(SMOTE(), model) never before the split
oversample mixed columns SMOTENC(categorical_features=CAT) raw categories, before encoding
choose a threshold by CV TunedThresholdClassifierCV(pipe, scoring="f1", cv=cv) see metrics
Splitter Use when Key arguments groups=
KFold regression, independent rows n_splits, shuffle, random_state —
StratifiedKFold classification as KFold —
RepeatedKFold, RepeatedStratifiedKFold small data: average several shuffles n_repeats —
ShuffleSplit, StratifiedShuffleSplit many random train/validation splits n_splits, test_size —
GroupKFold several rows per entity n_splits; shuffle from scikit-learn 1.6 required
StratifiedGroupKFold groups and a rare class n_splits, shuffle required
GroupShuffleSplit a random group-aware hold-out test_size required
LeaveOneGroupOut, LeavePGroupsOut few large groups n_groups required
TimeSeriesSplit time-ordered rows n_splits, test_size, gap, max_train_size —
LeaveOneOut tiny data — —
PredefinedSplit a validation set you fixed test_fold —
cv=5 (an int) quick checks StratifiedKFold(5) for classifiers, else KFold(5), no shuffle —
from sklearn.model_selection import GroupKFold, TimeSeriesSplit
rows = np.arange(10).reshape(-1, 1)
store = np.array(["A", "A", "B", "B", "B", "C", "C", "D", "E", "E"])
for k, (_, valid) in enumerate(GroupKFold(n_splits=3).split(rows, groups=store)):
print(f"fold {k}: valid stores {sorted(set(store[valid].tolist()))}")
ts = TimeSeriesSplit(n_splits=3, test_size=2, gap=1) # gap: rows skipped between
for train_idx, valid_idx in ts.split(rows):
print("train", train_idx.tolist(), "valid", valid_idx.tolist())
Output
fold 0: valid stores ['B']
fold 1: valid stores ['A', 'E']
fold 2: valid stores ['C', 'D']
train [0, 1, 2] valid [4, 5]
train [0, 1, 2, 3, 4] valid [6, 7]
train [0, 1, 2, 3, 4, 5, 6] valid [8, 9]
flowchart LR
    A{"Predict the future?"} -->|yes| T["TimeSeriesSplit"]
    A -->|no| B{"Several rows per entity?"}
    B -->|yes| G["GroupKFold /<br/>StratifiedGroupKFold"]
    B -->|no| C{"Classification?"}
    C -->|yes| S["StratifiedKFold"]
    C -->|no| K["KFold"]
from sklearn.model_selection import cross_val_predict, cross_val_score, cross_validate
auc = cross_val_score(pipe, X_train, y_train, cv=cv, scoring="roc_auc")
print(f"ROC-AUC {auc.mean():.3f} ± {auc.std():.3f}", auc.round(3))
res = cross_validate(pipe, X_train, y_train, cv=cv,
scoring={"auc": "roc_auc", "ap": "average_precision"},
return_train_score=True)
print(sorted(res))
print(f"train AUC {res['train_auc'].mean():.3f}",
f"valid AUC {res['test_auc'].mean():.3f}") # a small gap: no overfitting
oof = cross_val_predict(pipe, X_train, y_train, cv=cv, method="predict_proba")[:, 1]
print(oof.shape, oof[:3].round(3)) # each row predicted by a model that never saw it
Output
ROC-AUC 0.812 ± 0.011 [0.804 0.81 0.828 0.821 0.797]
['fit_time', 'score_time', 'test_ap', 'test_auc', 'train_ap', 'train_auc']
train AUC 0.818 valid AUC 0.812
(3750,) [0.003 0.208 0.022]
Function Returns Use for
cross_val_score(est, X, y, cv, scoring) one array of fold scores a quick estimate of one metric
cross_validate(..., scoring=[...] or {...}) a dict: test_<name>, fit_time, score_time several metrics; return_train_score, return_estimator, return_indices
cross_val_predict(..., method="predict_proba") one out-of-fold prediction per row plots, thresholds, stacking (not a score: folds are pooled)
n_jobs=-1 — folds in parallel
error_score="raise" — fail loudly instead of a NaN score
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import learning_curve, validation_curve
sizes, train_s, valid_s = learning_curve(
pipe, X_train, y_train, train_sizes=[0.1, 0.3, 1.0], cv=cv, scoring="roc_auc"
)
print("rows ", sizes, "\ntrain", train_s.mean(axis=1).round(3),
"\nvalid", valid_s.mean(axis=1).round(3))
hgb = Pipeline([("prep", prep), ("model", HistGradientBoostingClassifier(
learning_rate=0.1, random_state=42))])
train_s, valid_s = validation_curve(
hgb, X_train, y_train, param_name="model__max_leaf_nodes",
param_range=[2, 8, 32, 128], cv=cv, scoring="roc_auc",
)
print("train", train_s.mean(axis=1).round(3), "\nvalid", valid_s.mean(axis=1).round(3))
Output
rows [ 300 900 3000]
train [0.832 0.833 0.818]
valid [0.795 0.808 0.812]
train [0.854 0.918 0.993 1. ]
valid [0.84 0.842 0.826 0.814]
Pattern Diagnosis Next step
both curves low, close together underfitting (bias) more features, a more flexible model, less regularization
train high, validation much lower overfitting (variance) more data, regularize, a simpler model
validation still rising at the largest size more data will help collect rows
validation flat at the end more data will not help much better features or another model
validation peaks inside the range a good value is near the peak tune around it

LearningCurveDisplay.from_estimator(...) and ValidationCurveDisplay.from_estimator(...) take the same arguments and draw the curves with bands of ±1 standard deviation.

from scipy.stats import loguniform, randint
from sklearn.experimental import enable_halving_search_cv # noqa: F401
from sklearn.model_selection import (
GridSearchCV,
HalvingRandomSearchCV,
RandomizedSearchCV,
)
grids = [ # one dict per model family; the "model" step is swapped
{"model": [LogisticRegression(max_iter=1000)], "model__C": [0.01, 0.1, 1, 10]},
{"model": [HistGradientBoostingClassifier(random_state=42)],
"model__learning_rate": [0.05, 0.1], "model__max_leaf_nodes": [8, 31]},
]
grid = GridSearchCV(pipe, grids, cv=cv, scoring="roc_auc").fit(X_train, y_train)
print(grid.best_params_["model"], f"{grid.best_score_:.3f}")
table = pd.DataFrame(grid.cv_results_).sort_values("rank_test_score")
print(table[["rank_test_score", "mean_test_score", "std_test_score"]].head(3).round(3))
dists = {"model__learning_rate": loguniform(0.02, 0.3),
"model__max_leaf_nodes": randint(4, 64),
"model__l2_regularization": loguniform(1e-3, 10)}
rand = RandomizedSearchCV(hgb, dists, n_iter=6, cv=cv, scoring="roc_auc",
random_state=42).fit(X_train, y_train)
print(f"random best {rand.best_score_:.3f}")
print({k.split("__")[1]: np.round(v, 3).item() for k, v in rand.best_params_.items()})
halving = HalvingRandomSearchCV(hgb, dists, n_candidates=9, factor=3, cv=cv,
min_resources=400, # rows in the first round
scoring="roc_auc", random_state=42)
halving.fit(X_train, y_train)
print("halving rows per round", halving.n_resources_,
"candidates", halving.n_candidates_)
Output
HistGradientBoostingClassifier(random_state=42) 0.847
rank_test_score mean_test_score std_test_score
4 1 0.847 0.011
6 2 0.842 0.011
5 3 0.835 0.007
random best 0.842
{'l2_regularization': 0.022, 'learning_rate': 0.029, 'max_leaf_nodes': 6}
halving rows per round [400, 1200, 3600] candidates [9, 3, 1]
Search Tries Use when
GridSearchCV(est, param_grid) every combination 1–3 parameters, few values each
RandomizedSearchCV(est, param_distributions, n_iter) n_iter random draws 3+ parameters, continuous ranges
HalvingGridSearchCV, HalvingRandomSearchCV many candidates on few rows, the best on more many candidates; scores stable on small subsets
Optuna each trial guided by earlier trials expensive fits; conditional spaces
Argument Meaning
param_grid, param_distributions a dict (or list of dicts) of "step__param" → values or a distribution
scoring a name, a scorer, or a dict for several metrics
refit=True refit the best on all rows passed to fit; with several metrics: refit="auc"
cv a splitter object (shuffled, seeded)
n_iter, random_state random search budget and seed
factor, resource, min_resources, n_candidates halving: keep 1/factor per round; the resource is rows by default
return_train_score=True adds mean_train_score to see the gap
n_jobs=-1 fits in parallel
Attribute Holds
best_params_, best_score_ the winner and its mean CV score (optimistic)
best_estimator_ the winner refitted on all rows (with refit)
cv_results_ params, mean_test_score, std_test_score, rank_test_score, param_<name>
n_resources_, n_candidates_ halving: rows and candidates per round
SciPy distribution Draws Typical use
randint(low, high) integers low … high - 1 max_depth, n_neighbors, leaves
uniform(loc, scale) floats loc … loc + scale subsample, max_features
loguniform(a, b) floats evenly per order of magnitude C, alpha, learning_rate
a list one item, uniformly categorical options
import optuna
from sklearn.base import clone
optuna.logging.set_verbosity(optuna.logging.WARNING) # no log line per trial
def objective(trial: optuna.Trial) -> float:
model = clone(hgb).set_params(
model__learning_rate=trial.suggest_float("learning_rate", 0.02, 0.3, log=True),
model__max_leaf_nodes=trial.suggest_int("max_leaf_nodes", 4, 64, log=True),
model__min_samples_leaf=trial.suggest_int("min_samples_leaf", 5, 100),
)
return cross_val_score(model, X_train, y_train, cv=cv, scoring="roc_auc").mean()
sampler = optuna.samplers.TPESampler(seed=42, n_startup_trials=4) # default 10
study = optuna.create_study(direction="maximize", sampler=sampler)
study.optimize(objective, n_trials=8) # 4 random trials, then 4 guided by TPE
rounded = {name: round(value, 3) for name, value in study.best_params.items()}
print(round(study.best_value, 3), rounded)
best = clone(hgb).set_params(
**{f"model__{name}": value for name, value in study.best_params.items()}
)
best.fit(X_train, y_train) # Optuna does not refit: you do
Output
0.847 {'learning_rate': 0.136, 'max_leaf_nodes': 4, 'min_samples_leaf': 98}
Optuna Meaning
trial.suggest_int(name, low, high, step=1, log=False) an integer, both ends included
trial.suggest_float(name, low, high, log=False, step=None) a float; log=True for scale-free values
trial.suggest_categorical(name, choices) one item of a list
create_study(direction="maximize") "minimize" for an error
TPESampler(seed=42) reproducible; the first n_startup_trials=10 trials are random, so a short run needs a lower value
study.best_params, best_value, best_trial the winner
study.trials_dataframe() one row per trial
trial.report(value, step) + trial.should_prune() → raise optuna.TrialPruned() stop bad trials early with MedianPruner
study.optimize(objective, n_trials=50, timeout=600) a trial or time budget

The inner loop tunes; the outer loop scores the whole “tune, then refit” procedure on folds the search never saw.

inner = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
search = GridSearchCV(pipe, {"model__C": [0.01, 0.1, 1, 10]}, cv=inner,
scoring="roc_auc")
nested = cross_val_score(search, X_train, y_train, cv=outer, scoring="roc_auc")
search.fit(X_train, y_train) # the model you ship
print(f"nested {nested.mean():.3f} ± {nested.std():.3f} | "
f"best_score_ {search.best_score_:.3f}")
print("best C", search.best_params_["model__C"])
Output
nested 0.811 ± 0.010 | best_score_ 0.812
best C 0.1
Item Value
fits outer folds × inner folds × candidates (+ refits)
estimates the procedure, not one fixed model
the model you ship the search refitted on all training rows
report nested mean ± std, then one test-set score
from imblearn.over_sampling import SMOTENC
from imblearn.pipeline import make_pipeline as make_imb_pipeline
candidates = {
"plain": pipe,
"class_weight": clone(pipe).set_params(model__class_weight="balanced"),
"SMOTENC": make_imb_pipeline( # resamples the training folds only
SMOTENC(categorical_features=CAT, random_state=42), prep,
LogisticRegression(max_iter=1000)),
}
for name, model in candidates.items():
res = cross_validate(model, X_train, y_train, cv=cv,
scoring=["recall", "precision", "average_precision"])
print(f"{name:<12} recall {res['test_recall'].mean():.3f} "
f"precision {res['test_precision'].mean():.3f} "
f"AP {res['test_average_precision'].mean():.3f}")
Output
plain recall 0.285 precision 0.656 AP 0.554
class_weight recall 0.783 precision 0.378 AP 0.547
SMOTENC recall 0.766 precision 0.378 AP 0.538

Weights and resampling move the threshold: recall rises, precision falls, and the ranking (AP) barely changes. A tuned threshold on the plain model often does the same job (TunedThresholdClassifierCV).

Tool Import Notes
class weights class_weight="balanced" or {0: 1, 1: 5} weight of class cc = n/(k⋅nc)n / (k \cdot n_c); most models
positive weight (boosting) scale_pos_weight=n_neg / n_pos XGBoost, LightGBM
sample weights fit(X, y, sample_weight=w); in CV: params={"model__sample_weight": w} any per-row weight
random oversampling imblearn.over_sampling.RandomOverSampler duplicates rare rows
SMOTE imblearn.over_sampling.SMOTE(k_neighbors=5) numeric features only
SMOTENC SMOTENC(categorical_features=[...]) mixed numeric and categorical
SMOTEN imblearn.over_sampling.SMOTEN all categorical
random undersampling imblearn.under_sampling.RandomUnderSampler drops common rows; fast
pipeline with samplers imblearn.pipeline.Pipeline, make_pipeline samplers run in fit only, never in predict
threshold TunedThresholdClassifierCV, FixedThresholdClassifier often enough on its own
Trap Symptom Fix
cv=5 no shuffle; sorted data gives odd folds a seeded splitter with shuffle=True
a new splitter per model scores differ because of the folds one splitter object for every model
KFold with groups= the groups are ignored (and a warning) GroupKFold or StratifiedGroupKFold
shuffled CV on time series optimistic scores: the future leaks TimeSeriesSplit
preprocessing fitted before CV leakage, optimistic scores every learned step in the pipeline
SMOTE before the split recall and F1 far too high the sampler inside imblearn.pipeline
a sampler in a scikit-learn Pipeline TypeError: no transform imblearn.pipeline.Pipeline
plain SMOTE on one-hot columns fractional categories SMOTENC on raw categories, or class weights
best_score_ reported as the result biased upward nested CV or one test score
best value at the edge of the grid the optimum may lie outside widen the grid
uniform(0.5, 1.0) draws 0.5 to 1.5 uniform(loc, scale): uniform(0.5, 0.5)
"C" instead of "model__C" ValueError: Invalid parameter the step prefix; sorted(pipe.get_params())
the neg_ scores negative values flip the sign when you report
Optuna n_jobs>1 not reproducible n_jobs=1 with a seeded sampler
Optuna result used directly the model is not fitted rebuild with best_params and fit
cross_val_predict scored as CV a pooled score, not the fold mean cross_val_score for the estimate
tuning on the test set an optimistic final score tune with CV on the training set; test once
fold differences read as real noise picked as the winner compare paired fold scores; prefer the simpler model

scikit-learn’s HistGradientBoosting*, XGBoost and LightGBM build the same kind of model: many small trees, each fitted to the errors of the trees before it. They differ in parameter names, early stopping, category handling and logging. This page maps them side by side. The installed versions are scikit-learn 1.9, XGBoost 3.4 and LightGBM 4.7. The examples use data/customers.csv (churn). The blocks share one session:

import lightgbm as lgb
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from threadpoolctl import threadpool_limits
from xgboost import XGBClassifier
threadpool_limits(limits=1) # one OpenMP thread: faster on small tables
customers = pd.read_csv("data/customers.csv")
CAT = ["region", "plan", "contract", "payment_method"]
X = customers.drop(columns=["customer_id", "signup_date", "churned"])
y = customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
cat_dtypes = {c: pd.CategoricalDtype(sorted(X_train[c].unique())) for c in CAT}
def to_categories(df: pd.DataFrame) -> pd.DataFrame:
"""Apply the training categories; unseen values become NaN."""
out = df.copy()
for col, dtype in cat_dtypes.items():
out[col] = out[col].where(out[col].isin(dtype.categories)).astype(dtype)
return out
X_train, X_test = to_categories(X_train), to_categories(X_test)
X_fit, X_val, y_fit, y_val = train_test_split( # a validation set for early stopping
X_train, y_train, test_size=0.2, stratify=y_train, random_state=42
)
print(X_train.dtypes.map(str).value_counts().to_dict())
Output
{'int64': 5, 'category': 4, 'float64': 3}

threadpool_limits(limits=1) keeps the three libraries on one thread. On a few thousand rows, threads cost more than they save; scores do not change.

I want to… Use… Notes
a strong tabular model with no extra install HistGradientBoostingClassifier(), HistGradientBoostingRegressor() scikit-learn
the fastest training on large data lgb.LGBMClassifier(verbose=-1) leaf-wise trees
GPU training XGBClassifier(device="cuda")
use text columns as categories df[col].astype(pd.CategoricalDtype(train_categories)) all three read category
map unseen categories to missing s.where(s.isin(dtype.categories)).astype(dtype) no pandas 3 warning
early stopping in HGB early_stopping=True, n_iter_no_change=30, validation_fraction=0.2 "auto" only above 10,000 rows
early stopping in XGBoost XGBClassifier(early_stopping_rounds=50, eval_metric="auc"), fit(..., eval_set=[(X_val, y_val)]) settings in the constructor
early stopping in LightGBM fit(..., eval_X=X_val, eval_y=y_val, callbacks=[lgb.early_stopping(50, verbose=False)]) eval_set is deprecated in 4.7
the number of trees kept hgb.n_iter_, xgb.best_iteration + 1, lgbm.best_iteration_
predict with the first k trees xgb.predict_proba(X, iteration_range=(0, k)), lgbm.predict_proba(X, num_iteration=k)
the validation curve per round hgb.validation_score_, xgb.evals_result(), lgbm.evals_result_
a silent LightGBM verbose=-1 in the constructor
a silent XGBoost fit(..., verbose=False) verbosity=0 for warnings
the same LightGBM model on every run random_state=42, deterministic=True, force_row_wise=True
fewer threads on small data n_jobs=1 or threadpool_limits(limits=1) avoids oversubscription
weight the rare class scale_pos_weight=n_neg / n_pos (XGBoost, LightGBM), class_weight="balanced"
a monotonic effect monotonic_cst= (HGB), monotone_constraints= (XGBoost, LightGBM)
a quantile or Poisson model loss="quantile" / "poisson" (HGB), objective="quantile" (LightGBM)
gain importances xgb.feature_importances_, lgbm.booster_.feature_importance("gain")
model-agnostic importances sklearn.inspection.permutation_importance(model, X_val, y_val) all three
save the trees in a portable file xgb.save_model("m.json"), lgbm.booster_.save_model("m.txt")
load them back m = XGBClassifier(); m.load_model("m.json"); lgb.Booster(model_file="m.txt") Booster.predict gives P(class 1)
tune with CV RandomizedSearchCV or Optuna on the sklearn wrappers see CV and tuning
Task HistGradientBoosting XGBoost LightGBM
a classifier / regressor HistGradientBoostingClassifier / ...Regressor XGBClassifier / XGBRegressor LGBMClassifier / LGBMRegressor
the number of trees max_iter=100 n_estimators=100 n_estimators=100
the step size learning_rate=0.1 learning_rate=0.3 learning_rate=0.1
the tree size max_leaf_nodes=31, max_depth=None max_depth=6, max_leaves=0 num_leaves=31, max_depth=-1
the minimum rows per leaf min_samples_leaf=20 min_child_weight=1 (hessian sum) min_child_samples=20
an L2 penalty l2_regularization=0 reg_lambda=1 reg_lambda=0
an L1 penalty — reg_alpha=0 reg_alpha=0
a minimum gain to split — gamma=0 min_split_gain=0
row subsampling — subsample=1 subsample=1.0, subsample_freq=0 (set it to 1 to sample)
column subsampling max_features=1.0 (per split) colsample_bytree=1 colsample_bytree=1
histogram bins max_bins=255 max_bin=256 max_bin=255 (a constructor keyword)
early stopping early_stopping=True early_stopping_rounds=50 + eval_set callbacks=[lgb.early_stopping(50)] + eval_X, eval_y
the validation data internal validation_fraction=0.1 fit(..., eval_set=[(X_val, y_val)]) fit(..., eval_X=X_val, eval_y=y_val)
the monitored metric scoring="loss" eval_metric="auc" (constructor) fit(..., eval_metric="auc")
the trees used to predict n_iter_ best_iteration + 1 best_iteration_
native categories category dtype (categorical_features="from_dtype") category dtype (enable_categorical) category dtype (automatic)
missing values native native native
class imbalance class_weight="balanced" scale_pos_weight=n_neg / n_pos class_weight="balanced" or scale_pos_weight
monotonic effects monotonic_cst={"tenure_months": -1} monotone_constraints={"tenure_months": -1} monotone_constraints=[...] (one per column)
the loss loss="log_loss", "poisson", "quantile" objective="binary:logistic", "reg:squarederror" objective="binary", "regression", "quantile"
a seed random_state=42 random_state=42 random_state=42
threads OpenMP (threadpool_limits) n_jobs n_jobs
silence quiet by default verbose=False in fit; verbosity=0 verbose=-1 (constructor)
feature importances permutation_importance feature_importances_ (gain) feature_importances_ (importance_type="split")
save the model alone joblib.dump model.save_model("m.json") model.booster_.save_model("m.txt")
a GPU — device="cuda" device="gpu" (special build)

The numbers after = are the defaults in the installed versions.

hgb = HistGradientBoostingClassifier(
learning_rate=0.05, max_iter=1000, early_stopping=True, # "auto": only >10,000 rows
n_iter_no_change=30, validation_fraction=0.2, random_state=42,
).fit(X_train, y_train) # splits its own validation set from X_train
xgb = XGBClassifier(
n_estimators=1000, learning_rate=0.05, max_depth=4, early_stopping_rounds=50,
eval_metric="auc", random_state=42, n_jobs=1, # both in the constructor
).fit(X_fit, y_fit, eval_set=[(X_val, y_val)], verbose=False)
lgbm = lgb.LGBMClassifier(
n_estimators=1000, learning_rate=0.05, num_leaves=15, random_state=42,
n_jobs=1, verbose=-1,
).fit(X_fit, y_fit, eval_X=X_val, eval_y=y_val, eval_metric="auc",
callbacks=[lgb.early_stopping(50, verbose=False)])
used = {"hgb": hgb.n_iter_, "xgb": xgb.best_iteration + 1, "lgbm": lgbm.best_iteration_}
stored = {"hgb": hgb.n_iter_, "xgb": xgb.get_booster().num_boosted_rounds(),
"lgbm": lgbm.booster_.num_trees()}
for name, model in [("hgb", hgb), ("xgb", xgb), ("lgbm", lgbm)]:
auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
print(f"{name:<5} used {used[name]:>3} stored {stored[name]:>3}", f"AUC {auc:.3f}")
Output
hgb used 66 stored 66 AUC 0.829
xgb used 68 stored 118 AUC 0.836
lgbm used 45 stored 45 AUC 0.837
HistGradientBoosting XGBoost LightGBM
turn it on early_stopping=True ("auto" = on above 10,000 rows) early_stopping_rounds=k lgb.early_stopping(k) callback
validation data a fraction of fit’s rows (validation_fraction) eval_set=[(X_val, y_val)] (last pair is monitored) eval_X=, eval_y= (a tuple for several)
patience n_iter_no_change=10, tol=1e-7 early_stopping_rounds stopping_rounds, min_delta
monitored scoring="loss" or any scorer name the last eval_metric every metric; first_metric_only=True for one
after stopping keeps all n_iter_ trees, including the last n_iter_no_change that did not improve: no rollback stores every tree; predict uses best_iteration + 1 by default the booster holds best_iteration_ trees
best score validation_score_.max() (negative loss by default) best_score best_score_["valid_0"]["auc"]
history train_score_, validation_score_ evals_result()["validation_0"] evals_result_["valid_0"]
p_best = xgb.predict_proba(X_test)[:, 1] # best iteration by default
p_all = xgb.predict_proba(X_test, iteration_range=(0, stored["xgb"]))[:, 1]
p_20 = lgbm.predict_proba(X_test, num_iteration=20)[:, 1] # only the first 20 trees
print(f"xgb best {roc_auc_score(y_test, p_best):.3f}",
f"xgb all trees {roc_auc_score(y_test, p_all):.3f}",
f"lgbm 20 trees {roc_auc_score(y_test, p_20):.3f}")
print(list(xgb.evals_result()["validation_0"]), list(lgbm.evals_result_["valid_0"]))
Output
xgb best 0.836 xgb all trees 0.838 lgbm 20 trees 0.817
['auc'] ['auc', 'binary_logloss']

Here all 118 XGBoost trees score a little higher on the test set than the best 68: with 750 validation rows, the stopping point is noisy. Early stopping uses the validation rows to choose the number of trees, so they are no longer a fair test set. Keep a separate test set, as above, or choose the number of trees inside cross-validation.

HistGradientBoosting XGBoost LightGBM
how to mark category dtype; or categorical_features=["region", ...] or a boolean mask category dtype; enable_categorical is on by default in 3.4 category dtype; or fit(..., categorical_feature=[...])
text columns (str) ValueError: could not convert string to float ValueError about dtypes ValueError: pandas dtypes must be int, float or bool
unseen category at predict time treated as missing treated as missing treated as missing
cardinality limit at most max_bins (255) categories per column none none (rare ones merged via min_data_per_group)
split method partitions sorted by gradient partitions; one-hot below max_cat_to_onehot partitions; one-hot below max_cat_to_onehot=4
main knobs max_bins max_cat_to_onehot, max_cat_threshold cat_smooth, cat_l2, max_cat_threshold
new = X.loc[X_test.index[:2]].copy() # raw rows with text columns
new.loc[new.index[0], "region"] = "Central" # a region never seen in training
new = to_categories(new) # Central -> NaN, without a warning
print(new["region"].tolist())
print(lgbm.predict_proba(new)[:, 1].round(3), xgb.predict_proba(new)[:, 1].round(3))
Output
[nan, 'East']
[0.089 0.458] [0.105 0.456]

Build the CategoricalDtype once, from the training rows, and apply it to every later frame. astype(dtype) with values outside the categories still works in pandas 3.1, but it warns (Pandas4Warning) and will raise in a future version. Mask unknown values first, as to_categories does.

Need HistGradientBoosting XGBoost LightGBM
no training log default (verbose=0) fit(..., verbose=False); verbosity=0 silences warnings too verbose=-1 in the constructor
no early-stopping message — — lgb.early_stopping(50, verbose=False)
log every k rounds verbose=1 fit(..., verbose=k) callbacks=[lgb.log_evaluation(k)]
the same model on each run random_state=42 random_state=42 random_state=42
the same model across thread counts not guaranteed: fix the thread count not guaranteed: fix n_jobs deterministic=True, force_row_wise=True
GPU runs — can differ slightly between runs can differ slightly between runs
def fit_lgbm() -> np.ndarray:
model = lgb.LGBMClassifier(n_estimators=100, learning_rate=0.05, subsample=0.8,
subsample_freq=1, colsample_bytree=0.8,
random_state=42, n_jobs=1, verbose=-1,
deterministic=True, force_row_wise=True)
return model.fit(X_train, y_train).predict_proba(X_test)[:, 1]
print(np.array_equal(fit_lgbm(), fit_lgbm())) # same seed, same data: identical
Output
True
Type HistGradientBoosting XGBoost LightGBM Meaning
split count — get_score(importance_type="weight") importance_type="split" (default) how often a feature is used
gain — feature_importances_ (normalized "gain") importance_type="gain" the loss reduction it brings
cover — get_score(importance_type="cover") — rows affected
permutation permutation_importance(model, X_val, y_val) same same the score drop when shuffled; model-agnostic
SHAP shap.TreeExplainer (numeric features only; with native categories, shap.Explainer(model.predict_proba, masker)) predict(..., pred_contribs=True) on a DMatrix predict(X, pred_contrib=True) per-row contributions
imp = pd.DataFrame({
"lgbm_split": lgbm.feature_importances_,
"lgbm_gain": lgbm.booster_.feature_importance(importance_type="gain").round(0),
"xgb_gain": xgb.feature_importances_.round(3),
}, index=X_train.columns)
print(imp.sort_values("lgbm_gain", ascending=False).head(5))
Output
lgbm_split lgbm_gain xgb_gain
tenure_months 66 3089.0 0.261
contract 55 1774.0 0.234
monthly_charges 120 1319.0 0.058
age 135 1197.0 0.055
support_tickets 83 1194.0 0.097

Split counts favor continuous columns with many split points. Rank by gain or by permutation importance on validation data.

from pathlib import Path
Path("output").mkdir(exist_ok=True)
xgb.save_model("output/churn_xgb.json") # JSON: stable across XGBoost versions
lgbm.booster_.save_model("output/churn_lgbm.txt") # text: the best iteration only
xgb2 = XGBClassifier()
xgb2.load_model("output/churn_xgb.json")
booster = lgb.Booster(model_file="output/churn_lgbm.txt") # predict() gives P(class 1)
print(np.allclose(xgb2.predict_proba(X_test)[:, 1], p_best),
np.allclose(booster.predict(X_test), lgbm.predict_proba(X_test)[:, 1]))
Output
True True

A native file stores the trees only. Save the preprocessing (here the category lists) next to it, or save the whole pipeline with joblib.

  1. Fix learning_rate at 0.05–0.1 and let early stopping choose the number of trees.
  2. Tune the tree size: max_leaf_nodes / num_leaves (8–64) or max_depth (3–8).
  3. Tune the leaf size: min_samples_leaf / min_child_samples (10–200), min_child_weight (1–20).
  4. Add randomness: subsample 0.6–1 (LightGBM: with subsample_freq=1), colsample_bytree 0.5–1.
  5. Add penalties: l2_regularization / reg_lambda (log scale, 1e-3 to 10).
  6. Lower learning_rate for the final model and let early stopping add trees.
Native API XGBoost LightGBM
data xgboost.DMatrix(X, y, enable_categorical=True) lgb.Dataset(X, y)
train xgboost.train(params, dtrain, num_boost_round, evals=[(dval, "val")], early_stopping_rounds=50) lgb.train(params, dtrain, num_boost_round, valid_sets=[dval], callbacks=[...])
CV xgboost.cv(params, dtrain, nfold=5) lgb.cv(params, dtrain, nfold=5)
when custom objectives, ranking, very large data same
Trap Symptom Fix
LightGBM fit(eval_set=...) a deprecation warning in 4.7 eval_X= and eval_y=
LightGBM without verbose=-1 [LightGBM] [Info] ... lines on stdout verbose=-1 in the constructor
LightGBM subsample=0.8 alone no row sampling happens add subsample_freq=1
XGBoost early_stopping_rounds in fit TypeError in XGBoost 3 put it and eval_metric in the constructor
XGBoost fit without verbose=False one log line per round verbose=False
HGB on a small table early stopping is off ("auto" needs >10,000 rows) early_stopping=True
HGB n_iter_ read as the best round it includes the last n_iter_no_change rounds expected: HGB has no rollback
XGBoost predict after early stopping — uses the best iteration; pass iteration_range to change it
text (str) columns ValueError in all three category dtype, or encode
astype("category") on train and test separately different category lists one CategoricalDtype from the training rows
unseen values in astype(dtype) Pandas4Warning in pandas 3.1 mask them with where(isin(...)) first
HGB with more than 255 categories ValueError about cardinality TargetEncoder, or LightGBM / XGBoost
the early-stopping set used as the test set an optimistic score a separate test set
all cores on a small table, or several fits in parallel slow fits, oversubscription n_jobs=1 or threadpool_limits(limits=1)
criterion="friedman_mse" on GradientBoosting* deprecated in scikit-learn 1.9 leave the default
split-count importances high-cardinality columns rank first gain or permutation importance

Unsupervised learning finds structure without a target: groups of rows (clustering), a smaller set of columns (dimensionality reduction) and rows that do not fit (anomaly detection). This page covers the scikit-learn, SciPy and umap-learn tools for all three, how to choose their settings and how to check the result. The examples use data/customers.csv, data/sensors.csv and small synthetic sets. The blocks share one session:

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris, make_moons
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
behavior = ["tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "avg_session_minutes"]
X_cust = StandardScaler().fit_transform(customers[behavior]) # scale before distances
X_iris = StandardScaler().fit_transform(load_iris().data)
print(X_cust.shape, X_iris.shape)
Output
(5000, 5) (150, 4)
I want to… Use… Notes
put columns on one scale before distances StandardScaler() (RobustScaler() with outliers) first step of the pipeline
split rows into k round groups KMeans(n_clusters=k, n_init=10, random_state=42) default n_init="auto" runs once
cluster millions of rows MiniBatchKMeans(n_clusters=k, random_state=42) batch_size=
choose k silhouette_score per k + elbow of inertia_ sample_size= for big data
check that k is stable refit on bootstrap samples, adjusted_rand_score 5–20 resamples
describe each cluster df.groupby(labels)[cols].mean() + sizes original units, not scaled
label new rows (k-means) km.predict(X_new) nearest centroid
build a tree of merges scipy.cluster.hierarchy.linkage(X, method="ward") (n - 1) x 4 array
draw the tree dendrogram(Z, truncate_mode="lastp", p=20) Matplotlib
cut the tree into k groups fcluster(Z, t=k, criterion="maxclust") ids start at 1
hierarchical clustering in a pipeline AgglomerativeClustering(n_clusters=k, linkage="ward") fit_predict only
clusters of any shape, plus noise DBSCAN(eps=0.3, min_samples=5) noise label -1
choose eps k-distance curve: NearestNeighbors(n_neighbors=min_samples) the bend
density clusters without eps HDBSCAN(min_cluster_size=15) sklearn.cluster; no predict
label new rows after DBSCAN or HDBSCAN fit a classifier (k-NN) on the clustered rows noise rows excluded
soft cluster probabilities GaussianMixture(n_components=k).predict_proba(X) rows sum to 1
choose the number of mixture components lowest gmm.bic(X) try several covariance_type
keep 90% of the variance in fewer columns PCA(n_components=0.9) float = variance share
read what a component means pca.components_ as a DataFrame (loadings) signs are arbitrary
a scree plot pca.explained_variance_ratio_ and .cumsum()
a 2-D map of neighbors (picture only) TSNE(perplexity=30, random_state=42) no transform
a 2-D map that can place new rows umap.UMAP(random_state=42, n_jobs=1) n_neighbors, min_dist
check a 2-D map trustworthiness(X, emb, n_neighbors=10) 1 = neighbors kept
repeatable t-SNE numbers fit inside threadpool_limits(limits=1) threadpoolctl
flag anomalies fast, many columns IsolationForest(contamination=0.01, random_state=42) no scaling needed
flag local anomalies LocalOutlierFactor(n_neighbors=20).fit_predict(X) scale first
score new rows against clean data LocalOutlierFactor(novelty=True).fit(X_clean) then predict
a continuous anomaly score score_samples(X) lower = stranger
compare two clusterings adjusted_rand_score(a, b) ignores label names
compare a clustering with true labels adjusted_rand_score, normalized_mutual_info_score
Method You give it Cluster shape Noise label Scale first predict new rows Size
KMeans k round, similar sizes no yes yes millions
AgglomerativeClustering / linkage k or a cut height depends on linkage no yes no a few thousand
DBSCAN eps, min_samples any -1 yes no ~100,000
HDBSCAN min_cluster_size any, varying density -1 yes no ~100,000
GaussianMixture k, covariance_type ellipses no yes yes (+ probabilities) ~100,000
PCA components or a variance share linear — yes transform millions
TSNE perplexity local neighbors — yes no ~10,000
umap.UMAP n_neighbors, min_dist local + some global — yes transform 100,000s
IsolationForest contamination any -1 = anomaly no yes millions
LocalOutlierFactor n_neighbors, contamination local density -1 = anomaly yes only with novelty=True ~100,000

A first pass on tabular data: scale, run KMeans for k = 2…8, read the silhouette and the profiles. Try HDBSCAN when the groups are not round or when noise matters. Use a GaussianMixture when rows can belong to two groups.

from sklearn.cluster import KMeans
from sklearn.metrics import davies_bouldin_score, silhouette_score
rows = []
for k in range(2, 8):
km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X_cust)
sil = silhouette_score(X_cust, km.labels_, sample_size=2000, random_state=42)
rows.append((k, km.inertia_, sil, davies_bouldin_score(X_cust, km.labels_)))
scores = pd.DataFrame(rows, columns=["k", "inertia", "silhouette", "davies_bouldin"])
print(scores.round(3).to_string(index=False))
Output
k inertia silhouette davies_bouldin
2 20871.906 0.202 2.010
3 17715.065 0.172 1.732
4 15184.066 0.193 1.490
5 13217.303 0.204 1.357
6 12052.048 0.212 1.366
7 11495.821 0.167 1.569
Tool Best k Watch out
Elbow of inertia_ where the drop flattens always falls with k; the bend is often soft
silhouette_score highest, −1 to 1 O(n²): pass sample_size= and random_state=
davies_bouldin_score lowest, ≥ 0 favors round clusters
calinski_harabasz_score highest favors round clusters
Bootstrap ARI most stable across resamples slower, most honest
Profiles groups a team can act on the final judge

On behavior data the silhouette is often 0.2–0.3: the groups touch. That is normal. Here the silhouette is flat and Davies–Bouldin is lowest at k = 5, so the next block uses 5. Pick k from the scores and the profiles together.

km = KMeans(n_clusters=5, n_init=10, random_state=42).fit(X_cust)
profile = customers.groupby(km.labels_)[behavior].mean() # original units
profile["size"] = np.bincount(km.labels_)
profile["churn_rate"] = customers.groupby(km.labels_)["churned"].mean() # not a feature
print(profile.round(2).T) # one column per cluster
print(km.predict(X_cust[:3]), km.transform(X_cust[:1]).round(2)) # new rows, distances
Output
0 1 2 3 4
tenure_months 15.13 57.20 14.07 20.19 18.61
monthly_charges 52.05 56.95 48.59 58.41 97.56
support_tickets 0.53 1.00 2.77 1.06 0.95
logins_last_30d 9.22 10.60 10.22 23.82 9.76
avg_session_minutes 12.21 13.26 12.60 25.55 12.55
size 1550.00 819.00 1087.00 679.00 865.00
churn_rate 0.15 0.04 0.32 0.13 0.31
[1 1 1] [[3.4 1.87 4.18 3.64 3.03]]
Parameter or attribute Meaning
n_clusters k
init="k-means++" default: spread-out start centroids
n_init=10 10 starts; keeps the lowest inertia
max_iter=300 passes per start
labels_, cluster_centers_ cluster per training row; centroids in scaled space
inertia_ sum of squared distances to the own centroid
predict(X) / transform(X) nearest centroid / distance to every centroid
scaler.inverse_transform(km.cluster_centers_) centroids in original units

Name a cluster after the columns that differ most from the overall mean. Columns the model did not see, such as churned above, show whether the segments matter.

from scipy.cluster.hierarchy import cophenet, fcluster, linkage
from scipy.spatial.distance import pdist
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import adjusted_rand_score
Z = linkage(X_iris, method="ward") # rows: left id, right id, height, size
print(Z.shape, Z[-4:, 2].round(2)) # the last merges: cut below a big jump
tree_ids = fcluster(Z, t=3, criterion="maxclust") # 1-based ids
agg = AgglomerativeClustering(n_clusters=3, linkage="ward").fit_predict(X_iris)
print(np.bincount(tree_ids)[1:], adjusted_rand_score(tree_ids, agg))
print(round(cophenet(Z, pdist(X_iris))[0], 3)) # tree heights vs real distances
Output
(149, 4) [ 6.61 8. 12.64 27.25]
[49 30 71] 1.0
0.823
Linkage Distance between two clusters Result
ward rise in within-cluster variance compact, similar sizes; Euclidean only
complete farthest pair compact; sensitive to outliers
average mean over all pairs a middle ground; any metric
single closest pair long chains; follows curves
Cut Code
into k clusters fcluster(Z, t=k, criterion="maxclust")
at a height fcluster(Z, t=h, criterion="distance")
draw it dendrogram(Z, labels=names, color_threshold=h, orientation="right")
big trees dendrogram(Z, truncate_mode="lastp", p=20)
from sklearn.cluster import DBSCAN, HDBSCAN
from sklearn.neighbors import NearestNeighbors
X_moons = StandardScaler().fit_transform(
make_moons(n_samples=300, noise=0.08, random_state=42)[0]
)
dist, _ = NearestNeighbors(n_neighbors=5).fit(X_moons).kneighbors(X_moons)
print("k-distance, 90th/99th pct:", np.percentile(dist[:, -1], [90, 99]).round(2))
db = DBSCAN(eps=0.3, min_samples=5).fit(X_moons)
hdb = HDBSCAN(min_cluster_size=15, copy=True).fit(X_moons) # copy= avoids a warning
for name, labels in (("DBSCAN", db.labels_), ("HDBSCAN", hdb.labels_)):
n_clusters = len(set(labels.tolist()) - {-1}) # -1 is noise, not a cluster
print(name, "clusters:", n_clusters, "noise:", int((labels == -1).sum()))
Output
k-distance, 90th/99th pct: [0.22 0.31]
DBSCAN clusters: 2 noise: 0
HDBSCAN clusters: 2 noise: 7

Neither model can label new rows:

db.predict(X_moons[:2])
Output
AttributeError: 'DBSCAN' object has no attribute 'predict'

Train a classifier on the clustered rows instead:

from sklearn.neighbors import KNeighborsClassifier
kept = db.labels_ != -1 # drop the noise rows
knn = KNeighborsClassifier(n_neighbors=5).fit(X_moons[kept], db.labels_[kept])
print(knn.predict(X_moons[:5]), db.labels_[:5])
Output
[0 0 0 1 0] [0 0 0 1 0]
Setting Model Rule of thumb
eps DBSCAN the bend of the sorted k-distance curve (k = min_samples)
min_samples both about 2 × the number of features; larger = more noise
min_cluster_size HDBSCAN the smallest group you care about
metric both "euclidean" default; "cosine" for text vectors
Point type (DBSCAN) Rule Label
core ≥ min_samples points within eps, itself included cluster id
border within eps of a core point cluster id
noise neither -1

HDBSCAN (hierarchical DBSCAN) tries every eps and keeps the most stable clusters. It handles clusters of different densities. hdb.probabilities_ gives each row’s membership strength.

from sklearn.mixture import GaussianMixture
bic = {
(k, cov): GaussianMixture(k, covariance_type=cov, random_state=42).fit(X_iris)
.bic(X_iris)
for k in (2, 3, 4)
for cov in ("full", "diag")
}
print(min(bic, key=bic.get), round(min(bic.values()), 1)) # lowest BIC wins
gmm = GaussianMixture(n_components=3, random_state=42).fit(X_iris)
proba = gmm.predict_proba(X_iris) # one column per component, rows sum to 1
print(proba[:2].round(3), "unsure rows:", int((proba.max(axis=1) < 0.9).sum()))
Output
(2, 'full') 794.7
[[0. 1. 0.]
[0. 1. 0.]] unsure rows: 1
covariance_type Shape per component Parameters
"full" (default) any tilted ellipse most
"tied" one shared ellipse fewer
"diag" axis-aligned ellipses fewer
"spherical" circles, like k-means fewest

BIC picks 2 components here for the 3 iris species: two species overlap. BIC =pln⁡n−2ln⁡L^= p \ln n - 2 \ln \hat{L}, lower is better; aic penalizes less. Add n_init=5 for more restarts. gmm.score_samples(X) is a log density: low values are unusual rows.

from sklearn.decomposition import PCA
pca = PCA().fit(X_cust)
print(pca.explained_variance_ratio_.round(3)) # share per component
print(pca.explained_variance_ratio_.cumsum().round(3)) # running total
loadings = pd.DataFrame(pca.components_[:2].T, index=behavior, columns=["PC1", "PC2"])
print(loadings.round(2))
print(PCA(n_components=0.8).fit(X_cust).n_components_) # components for 80%
Output
[0.265 0.241 0.2 0.159 0.136]
[0.265 0.506 0.706 0.864 1. ]
PC1 PC2
tenure_months 0.00 -0.41
monthly_charges -0.09 -0.57
support_tickets 0.04 0.71
logins_last_30d 0.70 -0.06
avg_session_minutes 0.70 -0.05
4
Need Code
a 2-D projection PCA(n_components=2).fit_transform(X_scaled)
keep a variance share PCA(n_components=0.9)
back to the original space pca.inverse_transform(Z)
reconstruction error (anomaly score) ((X - pca.inverse_transform(pca.transform(X))) ** 2).sum(axis=1)
PCA before a model make_pipeline(StandardScaler(), PCA(0.9), KMeans(4, n_init=10))
sparse input (text) TruncatedSVD(n_components=100): no centering, any sparse size; PCA accepts sparse input only with the arpack or covariance_eigh solver (the default "auto" picks one)
unit-variance components PCA(whiten=True)

The five behavior columns are almost uncorrelated, so PCA needs 4 of 5 components for 80% of the variance. PCA compresses only correlated columns. PCA finds linear directions of maximum variance. The variance shares depend on the scaling, and the signs of the loadings can flip between versions. Read the pattern, not the sign.

import umap
from sklearn.manifold import TSNE, trustworthiness
from threadpoolctl import threadpool_limits
with threadpool_limits(limits=1): # t-SNE output depends on the thread count
emb_tsne = TSNE(perplexity=30, random_state=42).fit_transform(X_iris)
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=42, n_jobs=1)
emb_umap = reducer.fit_transform(X_iris) # random_state needs n_jobs=1
for name, emb in (("t-SNE", emb_tsne), ("UMAP", emb_umap)):
print(name, emb.shape, round(trustworthiness(X_iris, emb, n_neighbors=10), 3))
print(reducer.transform(X_iris[:2]).shape) # UMAP places new rows
Output
t-SNE (150, 2) 0.986
UMAP (150, 2) 0.975
(2, 2)
t-SNE UMAP
Import from sklearn.manifold import TSNE import umap (package umap-learn)
Main settings perplexity 5–50 (below n) n_neighbors 5–50, min_dist 0–0.5
New rows no transform reducer.transform(X_new)
Speed slow above ~10,000 rows faster
Repeatable random_state=42 + threadpool_limits(limits=1) random_state=42, n_jobs=1
Distances between clusters meaningless mostly meaningless
Use as model input no with care, inside a pipeline

Run PCA to about 50 components first when the data has hundreds of columns. Read a map only as “who is next to whom”. Check it with two seeds and two settings.

from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
s1 = pd.read_csv("data/sensors.csv").query("sensor_id == 'S1'")
cols = ["temperature_c", "humidity_pct", "vibration_mm_s"]
X_s1 = s1[cols].interpolate() # models reject NaN
iso = IsolationForest(n_estimators=200, contamination=0.01, random_state=42).fit(X_s1)
flags = iso.predict(X_s1) == -1 # -1 = anomaly, 1 = normal
print("flagged:", int(flags.sum()), "of", len(X_s1))
print(X_s1[flags].head(3))
lof = make_pipeline(StandardScaler(), LocalOutlierFactor(n_neighbors=20,
contamination=0.01))
print("LOF flagged:", int((lof.fit_predict(X_s1) == -1).sum()))
Output
flagged: 21 of 2016
temperature_c humidity_pct vibration_mm_s
584 20.09 57.60 7.53
820 22.92 54.40 7.53
876 36.03 50.65 1.81
LOF flagged: 21
Item IsolationForest LocalOutlierFactor
Idea anomalies need few random cuts to isolate lower density than its neighbors
Scale first no yes
Training rows fit_predict / predict: -1 anomaly fit_predict only
New rows predict, score_samples novelty=True, then predict
Score (lower = stranger) score_samples negative_outlier_factor_; score_samples with novelty=True
contamination the share of rows to flag; moves the threshold only same

Outlier detection: the anomalies are in the training data. Novelty detection: train on clean data, then score new rows. contamination is a quota: the model flags that share of training rows even if the data is clean. Without labels, use score_samples and inspect the strangest rows.

Metric Needs labels Range Question it answers
silhouette_score no −1 to 1, higher better are clusters separated?
davies_bouldin_score no ≥ 0, lower better compact vs separated
calinski_harabasz_score no ≥ 0, higher better between vs within variance
adjusted_rand_score yes, or a second clustering ~0 random, 1 identical do two partitions agree?
normalized_mutual_info_score yes 0 to 1 shared information
trustworthiness no 0 to 1 does a 2-D map keep neighbors?
gmm.bic(X) no lower better which mixture fits best?
Trap Symptom Fix
Unscaled columns the widest column (charges, tenure) decides every cluster or PC1 StandardScaler first, inside a pipeline
KMeans() with the default n_init="auto" different runs give different clusters n_init=10, random_state=42
Picking k by the lowest inertia “more clusters is always better” silhouette + elbow + profiles
Reading cluster ids as names “cluster 2” means something else after a rerun map ids to names once, from the profile; compare runs with ARI
Target or id columns in the features segments “explain” churn by construction cluster on behavior; use the target only to check
fcluster vs scikit-learn ids off-by-one when you compare fcluster starts at 1, scikit-learn at 0
Ward with a non-Euclidean metric ValueError average or complete linkage
DBSCAN with a guessed eps all rows are noise, or one big cluster k-distance curve
Counting -1 as a cluster one cluster too many len(set(labels) - {-1})
kneighbors(X) on the training rows the first neighbor is the row itself, distance 0 ask for one neighbor more, or read the last column
DBSCAN().predict or HDBSCAN().predict AttributeError k-NN classifier on the clustered rows
Lowest BIC read as the “true” number of groups BIC disagrees with the known classes BIC picks a density model; check the profiles
Gaps and sizes on a t-SNE or UMAP map false claims about which groups are similar read neighbors only; check with two seeds
t-SNE numbers change between machines same random_state, different output fit inside threadpool_limits(limits=1)
HDBSCAN(...) without copy= (scikit-learn 1.9) FutureWarning about copy pass copy=True
umap.UMAP(random_state=42) alone UserWarning about n_jobs add n_jobs=1
LocalOutlierFactor().predict(X) AttributeError fit_predict, or novelty=True for new rows
contamination far above the real rate many normal rows flagged start from a domain estimate; read score_samples
One anomaly model for several machines a whole machine flagged one model per machine, or add context columns
NaN in the input ValueError: Input X contains NaN impute or interpolate first

A time series is a sequence of values in time order. Order matters: the past can explain the future, never the reverse. This page covers the pandas date tools, decomposition, the statsmodels tests and models, lag features for machine learning, time-aware validation and forecast metrics. The examples use the daily visits in data/web_traffic.csv and the 10-minute readings in data/sensors.csv. The blocks share one session:

import numpy as np
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")
traffic = traffic.asfreq("D") # a fixed daily frequency; missing days become NaN rows
y = traffic["visits"].interpolate("time") # fill the 5 blank days
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
print(y.index.freqstr, len(y), int(traffic["visits"].isna().sum()), len(sensors))
Output
D 1096 5 8064
I want to… Use… Notes
parse dates while reading pd.read_csv(path, parse_dates=["date"], index_col="date") a DatetimeIndex
parse a text column pd.to_datetime(s, format="%Y-%m-%d") explicit format is faster and safer
calendar parts of a column s.dt.year, s.dt.month, s.dt.day_of_week, s.dt.hour Monday = 0
calendar parts of an index idx.month, idx.day_of_week, idx.day_name() no .dt
round timestamps s.dt.floor("h"), s.dt.normalize() normalize = midnight
attach and convert a time zone s.dt.tz_localize("UTC").dt.tz_convert("Europe/Berlin")
select a month or a year df.loc["2024-02"], df.loc["2023"] sorted index needed
select a date range df.loc["2024-12-01":"2024-12-07"] both ends included
fix the frequency, expose gaps df.asfreq("D") missing dates become NaN
all dates in a range pd.date_range("2024-01-01", periods=7, freq="D")
find missing dates full_range.difference(df.index)
downsample a flow (counts, money) df.resample("W").sum()
downsample a level (temperature, rate) df.resample("h").mean()
resample several series in a long table df.groupby("id").resample("h", on="ts")[cols].mean() or pivot first
fill a short gap s.interpolate("time", limit=3) smooth series
carry the last state forward s.ffill() prices, settings
a value k steps back s.shift(k) rows, not days
change from k steps back s.diff(k), s.pct_change(k)
a trailing mean as a feature s.shift(1).rolling(7).mean() no leak
an exponentially weighted mean s.ewm(span=7).mean() recent values weigh more
trend + seasonal + remainder STL(y, period=7, robust=True).fit() statsmodels
test for a unit root adfuller(y, result_object=True).pvalue H0: not stationary
test for stationarity kpss(y, regression="c", result_object=True) H0: stationary
autocorrelation values acf(y, nlags=28, result_object=True), pacf(y, nlags=28) alpha=0.05 adds bands
ACF and PACF plots plot_acf(y, lags=28, ax=ax), plot_pacf(...) statsmodels.graphics.tsaplots
fit seasonal ARIMA SARIMAX(y, order=(p, d, q), seasonal_order=(P, D, Q, s)) .fit(disp=False, maxiter=200)
check the fit converged res.mle_retvals["converged"]
a forecast with an interval res.get_forecast(h).summary_frame(alpha=0.05)
a known future input SARIMAX(y, exog=X), then res.forecast(h, exog=X_future)
a time-aware CV splitter TimeSeriesSplit(n_splits=5, test_size=h, gap=0) never shuffle
a baseline to beat seasonal naive: np.resize(train.iloc[-m:], h)
a scale-free error MASE: MAE ÷ in-sample seasonal naive MAE
stamps = pd.Series(pd.to_datetime(["2024-03-08 14:35", "2024-03-10 09:05"],
format="%Y-%m-%d %H:%M"))
parts = pd.DataFrame({
"day": stamps.dt.day_name(),
"dow": stamps.dt.day_of_week, # Monday = 0
"hour": stamps.dt.hour,
"floor_h": stamps.dt.floor("h"),
"berlin": stamps.dt.tz_localize("UTC").dt.tz_convert("Europe/Berlin"),
})
print(parts)
print(stamps.diff().iloc[1], (stamps.iloc[1] - pd.Timedelta(days=28)).date())
print(y.loc["2024-12-30":].to_string()) # both ends included
Output
day dow hour floor_h berlin
0 Friday 4 14 2024-03-08 14:00:00 2024-03-08 15:35:00+01:00
1 Sunday 6 9 2024-03-10 09:00:00 2024-03-10 10:05:00+01:00
1 days 18:30:00 2024-02-11
date
2024-12-30 7283.0
2024-12-31 7218.0
Freq: D
Offset alias Meaning Removed in pandas 3
"s", "min", "10min" seconds, minutes "S", "T"
"h" hours "H"
"D", "B" calendar days, business days
"W" (= "W-SUN"), "W-MON" weeks ending Sunday / Monday
"MS", "ME" month start, month end "M"
"QS", "QE" quarter start, quarter end "Q"
"YS", "YE" year start, year end "Y", "A"
Tool Does
idx.is_monotonic_increasing, idx.is_unique sorted and unique dates?
df.sort_index() sort before slicing by date
s.shift(1, freq="D") moves the index, not the values
pd.Timedelta(days=7), pd.DateOffset(months=1) fixed length / calendar-aware steps
s.dt.day_of_week not dt.weekday or dt.dayofweek (deprecated in pandas 3.1)
weekly = traffic.resample("W").agg({"visits": "sum", "bounce_rate": "mean"})
n_days = traffic["visits"].resample("W").size()
print(n_days.iloc[[0, -1]].to_string()) # partial bins at both ends
temp = sensors.pivot(index="timestamp", columns="sensor_id", values="temperature_c")
print(temp.resample("D").agg(["min", "max"]).iloc[:2, :4]) # level: min / max
feat = pd.DataFrame({"y": y, "ma7": y.rolling(7).mean(),
"ma7_lagged": y.shift(1).rolling(7).mean(),
"ewm7": y.ewm(span=7, adjust=False).mean()})
print(feat.iloc[6:8].round(1))
Output
date
2022-01-02 2
2025-01-05 2
Freq: 157W-SUN
sensor_id S1 S2
min max min max
timestamp
2024-05-01 19.13 24.96 21.29 38.03
2024-05-02 18.98 36.03 21.35 44.89
y ma7 ma7_lagged ewm7
date
2022-01-07 3155.0 3324.1 NaN 3289.5
2022-01-08 2912.0 3351.9 3324.1 3195.1
Column type Examples Downsample Upsample
flow sales, visits, spend sum split the value over the new periods
level temperature, price, rate mean, median, min, max ffill or interpolate
stock inventory, balance last ffill
Window Code Note
trailing mean s.rolling(7).mean() includes the current row
feature-safe trailing mean s.shift(1).rolling(7).mean() only the past
centered mean s.rolling(7, center=True).mean() plots only: uses the future
time-based window s.rolling("7D").mean() irregular timestamps
allow short windows s.rolling(7, min_periods=1) no leading NaN
running total or mean s.expanding().mean(), s.cumsum()
exponential weights s.ewm(span=7).mean(), ewm(halflife="3D", times=idx)
per group df.groupby("id")["x"].transform(lambda g: g.shift(1).rolling(7).mean()) no leak across groups
from statsmodels.tsa.seasonal import STL
stl = STL(np.log(y), period=7, robust=True).fit() # log: multiplicative effects
weekday = np.exp(stl.seasonal.groupby(y.index.day_of_week).mean())
print(weekday.round(3).to_dict()) # factor per weekday, Monday = 0
strength = 1 - stl.resid.var() / (stl.seasonal + stl.resid).var()
print(f"weekly strength {max(0, strength):.2f}")
Output
{0: 1.067, 1: 1.095, 2: 1.067, 3: 1.028, 4: 0.96, 5: 0.868, 6: 0.937}
weekly strength 0.35
Tool Use
STL(y, period=7, robust=True) robust to outliers; any period; .trend, .seasonal, .resid
STL(np.log(y), period=7) multiplicative seasonality through the log
seasonal_decompose(y, period=7, model="multiplicative") classical; NaN at both ends
MSTL(y, periods=(7, 365)) several seasonal periods
stl.plot(), then plt.show() data, trend, seasonal and remainder panels

Seasonal strength FS=max⁡(0,1−Var(R)/Var(S+R))F_S = \max(0, 1 - \text{Var}(R) / \text{Var}(S + R)): near 1 is strong.

A stationary series has a constant mean and variance and a correlation that depends only on the lag. ARIMA needs one; differencing (diff) often gives one.

from statsmodels.tsa.stattools import adfuller, kpss
for name, s, reg in [("level, c", y, "c"), ("level, ct", y, "ct"),
("diff, c", y.diff().dropna(), "c")]:
res = adfuller(s, regression=reg, result_object=True) # named fields
print(f"ADF {name:<10} stat={res.statistic:7.2f} p={res.pvalue:.2g}")
res = kpss(y.loc["2024"], regression="ct", nlags="auto", result_object=True)
print(f"KPSS 2024, ct stat={res.statistic:.3f} p={res.pvalue:.3f}",
res.critical_values["5%"])
Output
ADF level, c stat= -2.51 p=0.11
ADF level, ct stat= -5.29 p=5.8e-05
ADF diff, c stat= -10.89 p=1.2e-19
KPSS 2024, ct stat=0.204 p=0.014 0.146
Test H0 p below 0.05 means regression
adfuller unit root (not stationary) stationary "c" constant, "ct" trend, "n" none
kpss stationary not stationary "c" level, "ct" trend
ADF (H0: unit root) KPSS (H0: stationary) Read as
rejects does not reject stationary
does not reject rejects unit root: difference
rejects with "ct" only does not reject with "ct" trend-stationary: detrend or add a trend
rejects rejects the tests disagree: a break, a near unit root or a short window; difference or model the trend, then check the residuals
does not reject does not reject too little data to tell

Here the tests disagree. ADF with "ct" rejects a unit root, but KPSS with "ct" on 2024 rejects trend stationarity (0.204 is above the 5% critical value 0.146). This is common on a short window. Difference or model the trend, then check the residuals.

kpss p-values come from a table between 0.01 and 0.1. Outside it, kpss warns InterpolationWarning and the p-value is only a bound. Compare statistic with critical_values instead.

from statsmodels.tsa.stattools import acf, pacf
d = y.diff().dropna()
ac = acf(d, nlags=14, alpha=0.05, result_object=True) # named fields
r, ci = ac.acf, ac.confint # ci is centered on r
pr, pci = pacf(d, nlags=14, alpha=0.05)
lags = [1, 7, 14]
print("ACF ", r[lags].round(3), "band", (ci[lags, 1] - r[lags]).round(3))
print("PACF", pr[lags].round(3), "band", (pci[lags, 1] - pr[lags]).round(3))
Output
ACF [-0.012 0.178 0.213] band [0.059 0.065 0.069]
PACF [-0.012 0.034 0.068] band [0.059 0.059 0.059]

The ACF band uses Bartlett’s formula: it widens with the lag, because it allows for the correlation at earlier lags. The PACF band is flat at about ±1.96/n\pm 1.96/\sqrt{n}. The plots draw the bands around 0; a bar outside the band is significant.

Pattern Read as
ACF decays very slowly from near 1 trend or unit root: difference
ACF spikes at 7, 14, 21 weekly seasonality, s = 7
PACF cuts off after lag p, ACF decays AR(p)
ACF cuts off after lag q, PACF decays MA(q)
negative spike at lag s after a seasonal difference seasonal MA(1): Q = 1
all bars inside the band white noise: nothing left to model
from statsmodels.tsa.statespace.sarimax import SARIMAX
h = 28
train, test = y.iloc[:-h], y.iloc[-h:] # split by position, never shuffle
model = SARIMAX(np.log(train), order=(1, 1, 1), seasonal_order=(0, 1, 1, 7))
res = model.fit(disp=False, maxiter=200) # the default maxiter=50 may not converge
print(res.mle_retvals["converged"], round(res.aic, 1))
print(res.params.round(3).to_dict())
frame = np.exp(res.get_forecast(h).summary_frame(alpha=0.05)) # "mean" is now a median
print(frame[["mean", "mean_ci_lower", "mean_ci_upper"]].iloc[:2].round(0))
sarima_fc = frame["mean"].to_numpy()
Output
True -1788.8
{'ar.L1': 0.742, 'ma.L1': -0.979, 'ma.S.L7': -0.994, 'sigma2': 0.01}
visits mean mean_ci_lower mean_ci_upper
2024-12-04 7900.0 6468.0 9651.0
2024-12-05 7344.0 5710.0 9447.0

Both MA terms are near −1, which the Gotchas below list as a sign of over-differencing. Here the differences remove a trend and a weekly pattern that are almost fixed. The forecast still beats the baselines (see the metrics below), but estimates at the edge of −1 are unstable, and the intervals are less reliable. A usual alternative is day-of-week dummies as exog with d=1, D=0. After np.exp, the mean column of a log model is the median forecast, not the mean.

Template with a known future input (exogenous variable):

res = SARIMAX(y_train, exog=X_train, order=(1, 1, 1), seasonal_order=(0, 1, 1, 7),
trend="n").fit(disp=False, maxiter=200)
if not res.mle_retvals["converged"]: # simplify the model, log y or raise maxiter
raise RuntimeError("SARIMAX did not converge")
fc = res.get_forecast(steps=h, exog=X_future) # X_future must be known in advance
print(fc.summary_frame(alpha=0.05))
print(res.summary()) # coefficients, Ljung-Box and other residual tests
Part Meaning Choose with
d non-seasonal differences ADF / KPSS; usually 0 or 1
D, s seasonal differences at period s STL strength, ACF at s
p, P AR lags PACF cut-off
q, Q MA lags ACF cut-off
trend="c" drift (with d = 0: a constant)
comparing models lowest res.aic same d and D only
residual check res.plot_diagnostics(), acorr_ljungbox(res.resid, lags=[14])
s = pd.Series([10.0, 12.0, 14.0, 13.0, 15.0, 17.0],
index=pd.date_range("2024-01-01", periods=6, freq="D"))
lagged = pd.DataFrame({
"y": s,
"lag_1": s.shift(1), # yesterday
"lag_2": s.shift(2),
"mean_3": s.shift(1).rolling(3).mean(), # last 3 days, today excluded
"dow": s.index.day_of_week, # known in advance
})
print(lagged)
print(lagged.dropna().shape) # rows with a full history
Output
y lag_1 lag_2 mean_3 dow
2024-01-01 10.0 NaN NaN NaN 0
2024-01-02 12.0 10.0 NaN NaN 1
2024-01-03 14.0 12.0 10.0 NaN 2
2024-01-04 13.0 14.0 12.0 12.0 3
2024-01-05 15.0 13.0 14.0 13.0 4
2024-01-06 17.0 15.0 13.0 14.0 5
(3, 5)
Rule Why
every lag ≥ the forecast horizon (direct strategy) at forecast time, lags under h are not known yet
shift before rolling, expanding, ewm the window must end before the target row
calendar, holidays, planned promotions known in advance: safe
weather, competitor prices future values unknown: use lags or forecasts
per series: groupby("id")[col].shift(k) a plain shift crosses into the previous series
trees cannot extrapolate a trend model np.log(y), diff or a ratio to a recent level
asfreq before shift shift(7) is 7 rows; equal to 7 days only on a regular index
from sklearn.model_selection import TimeSeriesSplit
tss = TimeSeriesSplit(n_splits=3, test_size=2, gap=1) # gap: skipped rows
for fold, (tr, te) in enumerate(tss.split(np.arange(12)), start=1):
print(fold, "train", tr.min(), "to", tr.max(), "| test", te.tolist())
Output
1 train 0 to 4 | test [6, 7]
2 train 0 to 6 | test [8, 9]
3 train 0 to 8 | test [10, 11]
Argument Effect
n_splits number of folds; train always ends before test
test_size length of each test window: set it to the horizon
gap rows dropped between train and test: data delay, or lags shorter than h
max_train_size cap the train length: a sliding instead of an expanding window
cross_val_score(model, X, y, cv=tss) works with any scikit-learn model

The rows must be in time order. One row per time step; for several series in one table, split on the unique dates.

from sklearn.metrics import (
mean_absolute_error,
mean_absolute_percentage_error,
root_mean_squared_error,
)
def mase(actual, forecast, history, m=7):
hist = np.asarray(history)
scale = np.mean(np.abs(hist[m:] - hist[:-m])) # in-sample seasonal naive MAE
return mean_absolute_error(actual, forecast) / scale
forecasts = {
"naive": np.repeat(train.iloc[-1], h), # last value
"seasonal naive": np.resize(train.iloc[-7:].to_numpy(), h), # last week
"mean": np.repeat(train.iloc[-h:].mean(), h), # last 4 weeks
"SARIMA": sarima_fc,
}
table = pd.DataFrame({
name: {"MAE": mean_absolute_error(test, fc),
"RMSE": root_mean_squared_error(test, fc),
"MAPE %": 100 * mean_absolute_percentage_error(test, fc),
"MASE": mase(test, fc, train)}
for name, fc in forecasts.items()
}).T
print(table.round(2))
Output
MAE RMSE MAPE % MASE
naive 1750.14 1925.24 27.62 3.07
seasonal naive 837.64 1000.71 13.12 1.47
mean 731.52 850.87 11.36 1.28
SARIMA 430.74 546.18 6.38 0.76
Metric Formula Use
MAE 1n∑∣y−y^∣\frac{1}{n}\sum \lvert y - \hat y \rvert the data’s unit; robust
RMSE 1n∑(y−y^)2\sqrt{\frac{1}{n}\sum (y - \hat y)^2} big errors weigh more
MAPE 100n∑∣(y−y^)/y∣\frac{100}{n}\sum \lvert (y - \hat y)/y \rvert breaks at 0; scikit-learn returns a fraction
sMAPE 100n∑2∣y−y^∣∣y∣+∣y^∣\frac{100}{n}\sum \frac{2\lvert y - \hat y \rvert}{\lvert y \rvert + \lvert \hat y \rvert} 0 to 200
MASE MAE ÷ in-sample seasonal naive MAE scale-free; below 1 beats the naive
interval coverage ((lo <= y) & (y <= hi)).mean() should be near the nominal 95%
Baseline Forecast When it is hard to beat
naive the last value random walks, prices
seasonal naive the same day last season strong seasonality
mean / drift a recent mean, or a line through the first and last points stable or trending series

Report every model next to a baseline. A model that does not beat the seasonal naive is not ready.

Trap Symptom Fix
no parse_dates y.loc["2024"] raises KeyError; the index holds strings parse_dates= or pd.to_datetime
old offset aliases ValueError for "M", "H", "T", "Q", "Y" in pandas 3 "ME"/"MS", "h", "min", "QE", "YE"
dt.weekday, dt.dayofweek Pandas4Warning dt.day_of_week
index.inferred_freq Pandas4Warning asfreq("D") sets the frequency; read index.freqstr
partial "W" bins the first and last weekly sums are too small count rows per bin with .size(); drop partial bins
shift(7) on an irregular index lags of the wrong date asfreq first, or shift(7, freq="D")
rolling(7).mean() as a feature leakage: the window includes the target shift(1).rolling(7).mean()
bfill() or interpolation at the end values from the future ffill() at the forecast origin
ADF without result_object=True FutureWarning (statsmodels 0.15) adfuller(y, result_object=True)
KPSS without result_object=True FutureWarning kpss(y, result_object=True)
acf(..., alpha=0.05) without result_object=True FutureWarning about a plain tuple acf(..., result_object=True); read .acf, .confint
reading the ADF p-value backwards “p < 0.05, so it has a trend” ADF H0 is non-stationary: a small p supports stationarity
SARIMAX with the default maxiter=50 ConvergenceWarning fit(maxiter=200), check mle_retvals["converged"]
MA coefficient near −1 over-differencing, or an almost fixed trend or season drop one difference, use trend="c", or model the season with exog dummies
model on np.log(y) forecasts in log units np.exp the forecast and the interval
exog= at fit only forecast raises: exog needed pass future exog that is known in advance
KFold(shuffle=True) or train_test_split optimistic scores: the future leaks into training TimeSeriesSplit or a split by position
tuning on the holdout the final score is optimistic backtest with TimeSeriesSplit; look at the holdout once
MAPE with zeros inf or huge values MAE or MASE

Classic NLP (natural language processing) turns text into numeric vectors and then uses ordinary models on them. This page covers cleaning, the scikit-learn vectorizers and their settings, n-grams, classification pipelines, topic models, LSA (latent semantic analysis) and similarity search. The same tools work for log lines, support tickets, product titles and search boxes. The examples use data/reviews.csv. The blocks share one session:

import html
import re
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.pipeline import make_pipeline
pd.set_option("display.width", 100)
np.set_printoptions(precision=3, suppress=True)
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False) # "" stays a string
print(reviews.shape, reviews["sentiment"].value_counts().to_dict())
Output
(3000, 9) {'positive': 2066, 'negative': 596, 'neutral': 338}
I want to… Use… Notes
decode &amp;, &#39; html.unescape(text) before tokenizing
collapse whitespace re.sub(r"\s+", " ", text).strip()
split into word tokens re.findall(r"[a-z0-9']+", text.lower()) keeps don't
see the tokens a vectorizer makes vec.build_analyzer()(text) debug settings fast
word counts per document CountVectorizer() sparse matrix
counts weighted by rarity TfidfVectorizer() unit-length rows by default
1/0 presence instead of counts CountVectorizer(binary=True)
add two-word phrases ngram_range=(1, 2) not worth becomes a feature
drop rare terms and typos min_df=2 (documents) or min_df=0.01 (share)
drop terms in most documents max_df=0.5 corpus-specific stop words
cap the vocabulary max_features=20_000 most frequent terms
remove stop words stop_words="english" or a list not for sentiment
keep 1-letter tokens and digits token_pattern=r"(?u)\b\w+\b" default drops them
be robust to typos analyzer="char_wb", ngram_range=(3, 5)
use my own tokenizer tokenizer=f, token_pattern=None
dampen repeated words TfidfVectorizer(sublinear_tf=True) tf → 1 + ln(tf)
vectorize new text vec.transform(new_texts) never fit_transform
list the columns vec.get_feature_names_out()
classify text make_pipeline(TfidfVectorizer(), LogisticRegression(C=10)) input: a list of strings
a very fast baseline make_pipeline(CountVectorizer(), MultinomialNB())
tune vectorizer and model together GridSearchCV(pipe, {"tfidfvectorizer__min_df": [1, 2, 5]}) step__param
text + numeric columns ColumnTransformer([("txt", TfidfVectorizer(), "text"), ...]) the column name as a string
the most telling words pd.Series(clf.coef_[0], index=names).nlargest(10)
topics, non-negative factors NMF(n_components=10, init="nndsvda") on TF-IDF
topics, probabilistic LatentDirichletAllocation(n_components=10) on counts rows sum to 1
dense document vectors (LSA) make_pipeline(TruncatedSVD(100), Normalizer()) on TF-IDF
similar documents NearestNeighbors(metric="cosine").kneighbors(q) distance = 1 − cosine
cosine similarity matrix cosine_similarity(A, B) sklearn.metrics.pairwise
stack text and other features scipy.sparse.hstack([X_text, X_num]).tocsr()
def clean_text(text: str) -> str:
"""Decode HTML entities, lowercase and collapse whitespace."""
text = html.unescape(text) # &amp; -> &
text = text.lower()
return re.sub(r"\s+", " ", text).strip()
raw = " GREAT value &amp; FAST!!\n\nI&#39;ve ordered 2 more :) "
print(repr(clean_text(raw)))
print(re.findall(r"[a-z0-9']+", clean_text(raw))) # keeps contractions and digits
print(CountVectorizer().build_analyzer()(raw)) # the default pattern
print(CountVectorizer(token_pattern=r"(?u)\b\w+\b").build_analyzer()(raw))
Output
"great value & fast!! i've ordered 2 more :)"
['great', 'value', 'fast', "i've", 'ordered', '2', 'more']
['great', 'value', 'amp', 'fast', '39', 've', 'ordered', 'more']
['great', 'value', 'amp', 'fast', 'i', '39', 've', 'ordered', '2', 'more']
Step Keeps Loses Use when
html.unescape everything nothing always, first
lower() words shouting, names almost always (vectorizers do it by default)
collapse whitespace words layout always
remove punctuation re.sub(r"[^\w\s']", " ", t) words !!!, :(, ? punctuation carries no signal
replace numbers re.sub(r"\d+", "0", t) the fact “a number” the value prices, ids, dates
stop-word removal content words not, no, very topics, search; never sentiment
stemming / lemmatization base forms word forms small corpora; NLTK or spaCy
Token pattern "I've got 2 TVs!" gives
str.split() ["I've", 'got', '2', 'TVs!']
[a-z0-9']+ on lowercased text ["i've", 'got', '2', 'tvs']
(?u)\b\w\w+\b (scikit-learn default) ['ve', 'got', 'tvs']
(?u)\b\w+\b ['i', 've', 'got', '2', 'tvs']
docs = ["Not worth the money", "Worth every penny", "Not great, not terrible"]
count = CountVectorizer(ngram_range=(1, 2), min_df=1)
X = count.fit_transform(docs) # sparse documents x terms
print(X.shape, X.nnz, list(count.get_feature_names_out()[:6]))
print(pd.DataFrame(X.toarray(), columns=count.get_feature_names_out()).iloc[:, :6])
tfidf = TfidfVectorizer().fit(docs)
idf = pd.Series(tfidf.idf_, index=tfidf.get_feature_names_out())
print(idf[["not", "worth", "money"]].round(2).to_dict()) # rarer term, higher idf
print(tfidf.transform(["not worth it"]).toarray().round(2)) # unknown "it" ignored
Output
(3, 16) 18 ['every', 'every penny', 'great', 'great not', 'money', 'not']
every every penny great great not money not
0 0 0 0 0 1 1
1 1 1 0 0 0 0
2 0 0 1 1 0 2
{'not': 1.29, 'worth': 1.29, 'money': 1.69}
[[0. 0. 0. 0.71 0. 0. 0. 0.71]]
Parameter Default Effect
lowercase True lowercase before tokenizing
token_pattern r"(?u)\b\w\w+\b" regex for one token: 2+ word characters
tokenizer None a function str -> list[str]; set token_pattern=None
preprocessor None a function applied to each raw text first
stop_words None "english" (318 words) or your own list
ngram_range (1, 1) (1, 2) adds bigrams, (2, 2) bigrams only
analyzer "word" "char" or "char_wb": character n-grams
min_df 1 int = minimum document count, float = minimum share
max_df 1.0 drop terms in more than this share of documents
max_features None keep the N most frequent terms
vocabulary None a fixed term list; nothing is learned
binary False 1 if a term is present
dtype int64 / float64 np.float32 halves the memory
TfidfVectorizer only Default Effect
use_idf True multiply term counts by idf
smooth_idf True idf =ln⁡1+n1+df+1= \ln\frac{1 + n}{1 + \text{df}} + 1
sublinear_tf False tf → 1+ln⁡(tf)1 + \ln(\text{tf})
norm "l2" unit-length rows, so a dot product is the cosine
Fitted attribute Gives
vocabulary_ term → column index
get_feature_names_out() column names in order
idf_ the idf weight per column (TF-IDF only)
for name, vec in [
("words 1-2", CountVectorizer(ngram_range=(1, 2))),
("words 1-2, min_df=5", CountVectorizer(ngram_range=(1, 2), min_df=5)),
("char_wb 3-5", CountVectorizer(analyzer="char_wb", ngram_range=(3, 5), min_df=5)),
]:
print(f"{name:<20}", vec.fit_transform(reviews["text"]).shape[1], "columns")
char3 = CountVectorizer(analyzer="char_wb", ngram_range=(3, 3)).build_analyzer()
print(char3("qualty")) # a typo still shares qua, ual with "quality"
Output
words 1-2 3553 columns
words 1-2, min_df=5 1418 columns
char_wb 3-5 3870 columns
[' qu', 'qua', 'ual', 'alt', 'lty', 'ty ']
Setting Captures Cost
unigrams (1, 1) single words smallest vocabulary
(1, 2) negation and phrases: not worth, love it 3–5× the columns: add min_df
(1, 3) longer phrases rarely worth it on short texts
analyzer="char_wb", (3, 5) spelling, typos, word parts many columns; slower
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
binary = reviews[reviews["sentiment"] != "neutral"]
X_train, X_test, y_train, y_test = train_test_split(
binary["text"], binary["sentiment"], test_size=0.25,
stratify=binary["sentiment"], random_state=42,
)
clf = make_pipeline(
TfidfVectorizer(preprocessor=clean_text, ngram_range=(1, 2), min_df=2),
LogisticRegression(C=10, max_iter=1000), # the default C=1 underfits TF-IDF
).fit(X_train, y_train) # the vectorizer learns from the training texts only
print(classification_report(y_test, clf.predict(X_test), digits=3))
print(clf.predict(["Not worth the money.", "Sturdy and built to last."]))
Output
precision recall f1-score support
negative 0.809 0.826 0.817 149
positive 0.949 0.944 0.947 517
accuracy 0.917 666
macro avg 0.879 0.885 0.882 666
weighted avg 0.918 0.917 0.918 666
['negative' 'positive']

Tune the vectorizer and the model together. Step names are the lowercased class names:

from sklearn.model_selection import GridSearchCV
grid = GridSearchCV(clf, {
"tfidfvectorizer__ngram_range": [(1, 1), (1, 2)],
"tfidfvectorizer__min_df": [1, 2, 5],
"logisticregression__C": [1, 10, 100],
}, cv=5, scoring="f1_macro", n_jobs=-1).fit(X_train, y_train)
print(grid.best_params_, grid.best_score_)
Model Input Strengths Watch out
LogisticRegression TF-IDF probabilities, readable weights tune C; class_weight="balanced"
MultinomialNB counts very fast; good on small data overconfident probabilities; tune alpha
ComplementNB counts naive Bayes for imbalanced classes
LinearSVC TF-IDF often the most accurate linear model no predict_proba
SGDClassifier TF-IDF huge corpora, partial_fit tune alpha
trees, k-NN — rarely good on sparse text

Read the weights of a linear model:

names = clf[0].get_feature_names_out()
weights = pd.Series(clf[-1].coef_[0], index=names) # > 0 pushes to classes_[1]
print(clf[-1].classes_, weights.nlargest(4).round(2).to_dict())
print(weights.nsmallest(4).round(2).to_dict())
Output
['negative' 'positive'] {'premium': 4.2, 'one wore': 3.45, 'excellent': 3.23, 'quickly': 3.16}
{'avoid': -4.62, 'not': -3.92, 'disappointing': -3.76, 'confusing': -3.56}

one wore is a rare bigram with a large weight. Rare n-grams get noisy weights; read weights from a model with a higher min_df.

from sklearn.decomposition import NMF, LatentDirichletAllocation
texts = reviews["text"].map(clean_text)
counts_vec = CountVectorizer(stop_words="english", min_df=5, max_df=0.5)
counts = counts_vec.fit_transform(texts)
lda = LatentDirichletAllocation(n_components=6, learning_method="batch",
random_state=42).fit(counts)
tfidf_vec = TfidfVectorizer(stop_words="english", min_df=5, max_df=0.5)
nmf = NMF(n_components=6, init="nndsvda", random_state=42, max_iter=1000)
W = nmf.fit_transform(tfidf_vec.fit_transform(texts)) # documents x topics
def top_words(components, terms, n=5):
return [" ".join(terms[np.argsort(row)[::-1][:n]]) for row in components]
print(*top_words(lda.components_[:3], counts_vec.get_feature_names_out()), sep="\n")
print(*top_words(nmf.components_[:3], tfidf_vec.get_feature_names_out()), sep="\n")
print(lda.transform(counts[:1]).round(2), lda.transform(counts[:1]).sum().round(2))
Output
customer great service arrived package
price quality point purchase happy
size sturdy built recommend friends
months lasted delivery money value
battery charge holds days fast
sturdy built recommend friends definitely
[[0.02 0.35 0.02 0.55 0.02 0.02]] 1.0
NMF LatentDirichletAllocation
Input TF-IDF raw counts
Model X≈WHX \approx WH, all values ≥ 0 documents mix topics; topics are word distributions
transform output topic weights topic probabilities (rows sum to 1)
Short texts usually cleaner topics often mixed topics
Speed fast slower
Repeatable random_state=42 random_state=42

Choose n_components by reading the top words: the smallest number of distinct topics you can name. Remove stop words and set max_df first, or every topic starts with the.

from sklearn.decomposition import TruncatedSVD
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import Normalizer
lsa = make_pipeline(
TfidfVectorizer(preprocessor=clean_text, stop_words="english", min_df=2),
TruncatedSVD(n_components=50, random_state=42), # no centering: stays sparse
Normalizer(), # unit rows: dot product = cosine
)
vectors = lsa.fit_transform(reviews["text"])
nn = NearestNeighbors(n_neighbors=3, metric="cosine").fit(vectors)
dist, idx = nn.kneighbors(lsa.transform(["the battery dies too fast"]))
print(vectors.shape, (1 - dist).round(3)) # cosine similarity = 1 - distance
for text in reviews["text"].iloc[idx[0]]:
print(text.strip()[:60])
Output
(3000, 50) [[0.996 0.835 0.822]]
The battery drains fast.
Bought this for my dad. The battery charges fast and holds t
The battery charges fast &amp; holds teh charge.
Representation Dimensions Similar words close? Needs a download
bag of words / TF-IDF one per term, sparse no no
character n-grams one per letter sequence by spelling no
LSA (TruncatedSVD) 50–300, dense yes, learned from your corpus no
word2vec, GloVe, fastText 100–300 per word yes yes
transformer sentence embeddings 384–1,024 per text yes, in context yes
Similarity search Code
on sparse TF-IDF NearestNeighbors(metric="cosine").fit(X_tfidf) (brute force)
on unit vectors scores = vectors @ query; np.argsort(-scores)[:k]
all pairs cosine_similarity(X) (n × n: small n only)
duplicate detection pairs with cosine above 0.9
Trap Symptom Fix
fitting the vectorizer on all data optimistic CV scores put it in a Pipeline
fit_transform on new text different columns; shape mismatch transform
passing a one-column DataFrame a vocabulary of one term: the column name pass a Series: df["text"]
stop_words="english" for sentiment not worth becomes worth keep stop words; use bigrams
default token_pattern i've → ve; 2 and x vanish token_pattern=r"(?u)\b\w+\b" or your own
HTML entities left in tokens amp, 39 html.unescape first
keep_default_na left on a review text "NA" or "" becomes NaN; the vectorizer fails read_csv(..., keep_default_na=False)
bigrams without min_df a huge, noisy vocabulary min_df=2 or more, max_features
.toarray() on a corpus memory error stay sparse; densify single rows
the default C=1 on TF-IDF underfitting tune C (10 is a common start)
reading weights of rare n-grams big, meaningless weights require a higher min_df before reading weights
accuracy on imbalanced classes a weak minority class is hidden per-class recall; compare with DummyClassifier
LDA on TF-IDF poor topics LDA takes counts
PCA(svd_solver="randomized") or "full" on sparse TF-IDF TypeError; the default solver runs but centers the data (not LSA) TruncatedSVD: no centering, the standard for LSA
a query of unknown words a zero vector; no or random neighbors check X_query.nnz > 0
Euclidean k-NN on raw TF-IDF long documents look far away metric="cosine" or unit rows

PyTorch is a tensor library with automatic differentiation and building blocks for neural networks. This page covers the parts you use in every project: tensors, autograd, models, data loading, losses, optimizers, a complete training loop, regularization, checkpoints and reproducibility. Everything runs on the CPU. The examples use data/customers.csv (churn). The blocks share one session:

import copy
import numpy as np
import pandas as pd
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset, TensorDataset
torch.set_num_threads(1) # repeatable sums; no clash with other processes
torch.manual_seed(42) # weights, dropout, torch.rand*
print(torch.get_num_threads(), torch.rand(3))
Output
1 tensor([0.8823, 0.9150, 0.3829])
I want to… Use… Notes
a tensor from a list torch.tensor([1.0, 2.0]) copies; float32
a float32 tensor from NumPy torch.as_tensor(arr, dtype=torch.float32) NumPy is float64
a NumPy array back t.detach().numpy() shares memory
one Python number t.item() loss.item()
change the dtype t.float(), t.long(), t.to(torch.int64)
reshape t.reshape(n, -1), t.unsqueeze(1), t.squeeze(1) -1 = infer
reduce over rows t.mean(dim=0) keepdim=True keeps the axis
join tensors torch.cat([a, b], dim=0), torch.stack([a, b]) stack adds a dimension
track gradients torch.tensor(1.0, requires_grad=True) leaf tensor
compute gradients loss.backward(), then w.grad gradients add up
run without a graph with torch.no_grad(): prediction, updates
write a model subclass nn.Module, define forward layers in __init__
chain layers nn.Sequential(nn.Linear(7, 32), nn.ReLU(), ...)
count parameters sum(p.numel() for p in model.parameters())
wrap arrays as a dataset TensorDataset(X, y)
a dataset from a DataFrame subclass Dataset: __len__, __getitem__
shuffled mini-batches DataLoader(ds, batch_size=64, shuffle=True, generator=g) g = seeded torch.Generator
a regression loss nn.MSELoss(), nn.L1Loss(), nn.HuberLoss() float targets
a binary loss nn.BCEWithLogitsLoss(pos_weight=w) raw logits in
a multiclass loss nn.CrossEntropyLoss() int64 class indices
a default optimizer torch.optim.AdamW(model.parameters(), lr=1e-3)
weight decay AdamW(..., weight_decay=0.01) decoupled L2
lower the rate on a plateau lr_scheduler.ReduceLROnPlateau(opt, patience=3) sched.step(val_loss)
dropout nn.Dropout(p=0.3) after an activation train mode only
switch dropout and batch norm model.train() / model.eval() not the same as no_grad
probabilities from logits torch.sigmoid(z), z.softmax(dim=1)
the predicted class z.argmax(dim=1)
keep the best weights copy.deepcopy(model.state_dict()) not a reference
save weights torch.save({"config": cfg, "state_dict": sd}, path)
load weights safely torch.load(path, weights_only=True) the default since PyTorch 2.6; write it for older versions
pick a device device = "cuda" if torch.cuda.is_available() else "cpu" torch.backends.mps.is_available() on Apple
move a model and a batch model.to(device), xb.to(device) in the loop the same device for both
a GPU tensor as NumPy t.detach().cpu().numpy() .cpu() first
repeatable runs torch.manual_seed(42), torch.set_num_threads(1) plus a seeded generator
X = torch.arange(12.0).reshape(3, 4) # 3 rows, 4 features
print(X.shape, X.dtype, X[:, 0].shape, X[:, :1].shape, X.unsqueeze(0).shape)
print(X.sum(dim=0), X.argmax(dim=1), (X @ torch.ones(4)).tolist())
Z = (X - X.mean(dim=0)) / X.std(dim=0, correction=0) # broadcasting, like NumPy
print(Z[0], torch.from_numpy(np.ones(2)).dtype) # NumPy float64 stays float64
Output
torch.Size([3, 4]) torch.float32 torch.Size([3]) torch.Size([3, 1]) torch.Size([1, 3, 4])
tensor([12., 15., 18., 21.]) tensor([3, 3, 3]) [6.0, 22.0, 38.0]
tensor([-1.2247, -1.2247, -1.2247, -1.2247]) torch.float64
dtype Use Convert
float32 features, weights, MSE and BCE targets .float()
float64 NumPy default; gradient checks .double()
int64 class indices for CrossEntropyLoss, nn.Embedding input .long()
bool masks: t[t > 0]
Shape tool Effect
reshape(a, b) / view(a, b) new shape; view needs contiguous memory
unsqueeze(d) / squeeze(d) add / remove a size-1 dimension
flatten(start_dim=1) keep the batch dimension, join the rest
t.T, permute(0, 2, 3, 1) swap / reorder dimensions
cat(dim=0) / stack() join along an existing / a new dimension
NumPy interop Copies dtype
torch.from_numpy(arr) no, shared memory kept
torch.as_tensor(arr, dtype=torch.float32) only if the dtype changes as asked
torch.tensor(arr) always kept
t.numpy() no, shared memory kept; fails if requires_grad
t.detach().numpy() no safe for tensors in a graph
w = torch.tensor(2.0, requires_grad=True)
loss = (3.0 * w - 5.0) ** 2 # dL/dw = 6 * (3w - 5) = 6
loss.backward()
print(w.grad)
with torch.no_grad(): # update outside the graph
w -= 0.1 * w.grad
w.grad.zero_() # backward() adds to .grad: reset it
print(round(w.item(), 2), w.grad)
Output
tensor(6.)
1.4 tensor(0.)
Rule Code
gradients accumulate optimizer.zero_grad() before every backward()
update weights outside the graph with torch.no_grad(): w -= lr * w.grad
leave the graph to plot or store t.detach()
sum losses for logging total += loss.item(), not total += loss
only leaf tensors keep .grad create weights with requires_grad=True
class MLP(nn.Module):
"""n_features -> hidden layers -> n_out logits."""
def __init__(self, n_features: int, hidden: tuple[int, ...] = (32, 16),
n_out: int = 1, dropout: float = 0.0) -> None:
super().__init__() # always first
layers: list[nn.Module] = []
sizes = (n_features, *hidden)
for size_in, size_out in zip(sizes[:-1], sizes[1:], strict=True):
layers += [nn.Linear(size_in, size_out), nn.ReLU(), nn.Dropout(dropout)]
layers.append(nn.Linear(sizes[-1], n_out))
self.net = nn.Sequential(*layers) # registered: its weights are parameters
self.n_out = n_out
def forward(self, x: torch.Tensor) -> torch.Tensor:
out = self.net(x)
return out.squeeze(1) if self.n_out == 1 else out # (n,) or (n, K)
model = MLP(7)
print(sum(p.numel() for p in model.parameters()), model(torch.zeros(5, 7)).shape)
print([name for name, _ in model.named_parameters()][:2])
Output
801 torch.Size([5])
['net.0.weight', 'net.0.bias']
Layer Shape in → out Parameters
nn.Linear(i, o) (n, i) → (n, o) i·o + o
nn.ReLU(), nn.GELU(), nn.Tanh() same 0
nn.Dropout(p) same 0
nn.BatchNorm1d(f), nn.LayerNorm(f) (n, f) → (n, f) 2f
nn.Embedding(v, d) (n,) int64 → (n, d) v·d
nn.Conv2d(c, k, 3, padding=1) (n, c, H, W) → (n, k, H, W) k·c·9 + k
nn.MaxPool2d(2) (n, c, H, W) → (n, c, H/2, W/2) 0
nn.Flatten() (n, c, H, W) → (n, c·H·W) 0

Layers created in __init__ as attributes (or inside nn.Sequential, nn.ModuleList) are registered. A plain Python list of layers is not: its weights are invisible to the optimizer and to state_dict().

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
customers = pd.read_csv("data/customers.csv")
features = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d",
"avg_session_minutes", "has_autopay", "age"]
train_df, valid_df = train_test_split(customers, test_size=0.2,
stratify=customers["churned"], random_state=42)
scaler = StandardScaler().fit(train_df[features]) # fit on training rows only
class ChurnDataset(Dataset):
def __init__(self, df: pd.DataFrame) -> None:
self.X = torch.as_tensor(scaler.transform(df[features]), dtype=torch.float32)
self.y = torch.tensor(df["churned"].to_numpy(), dtype=torch.float32) # copy
def __len__(self) -> int:
return len(self.y)
def __getitem__(self, i: int) -> tuple[torch.Tensor, torch.Tensor]:
return self.X[i], self.y[i]
train_ds, valid_ds = ChurnDataset(train_df), ChurnDataset(valid_df)
g = torch.Generator().manual_seed(42) # repeatable shuffling
train_loader = DataLoader(train_ds, batch_size=64, shuffle=True, generator=g)
valid_loader = DataLoader(valid_ds, batch_size=256) # no shuffle for evaluation
xb, yb = next(iter(train_loader))
print(len(train_ds), len(train_loader), xb.shape, xb.dtype, yb.shape)
Output
4000 63 torch.Size([64, 7]) torch.float32 torch.Size([64])
DataLoader argument Effect
batch_size=64 rows per optimizer step
shuffle=True new order every epoch: training only
generator=torch.Generator().manual_seed(42) repeatable order
drop_last=True skip the last, smaller batch
num_workers=2 load in subprocesses; needs if __name__ == "__main__": in scripts
collate_fn=f custom batching (padding variable-length sequences)
TensorDataset(X, y) the quick dataset for tensors already in memory
Task Last layer Loss Model output Target Predict
regression Linear(h, 1) MSELoss(), L1Loss(), HuberLoss() float (n,) float (n,) the output
binary Linear(h, 1) BCEWithLogitsLoss(pos_weight=w) logits (n,) float 0./1. (n,) torch.sigmoid(z)
multiclass Linear(h, K) CrossEntropyLoss(weight=w) logits (n, K) int64 (n,) in 0..K-1, or float probabilities (n, K) z.softmax(1), z.argmax(1)
multilabel Linear(h, K) BCEWithLogitsLoss() logits (n, K) float 0./1. (n, K) torch.sigmoid(z) > 0.5
logits = torch.tensor([2.0, -1.0, 0.5])
print(round(nn.BCEWithLogitsLoss()(logits, torch.tensor([1.0, 0.0, 1.0])).item(), 4))
scores = torch.tensor([[2.0, 0.1, -1.0], [0.0, 1.5, 0.2]]) # (n=2, K=3)
print(round(nn.CrossEntropyLoss()(scores, torch.tensor([0, 1])).item(), 4))
print(scores.softmax(dim=1).sum(dim=1), scores.argmax(dim=1))
Output
0.3048
0.2922
tensor([1., 1.]) tensor([0, 1])

The wrong target dtype fails loudly:

nn.CrossEntropyLoss()(scores, torch.tensor([0.0, 1.0])) # float labels of shape (n,)
Output
RuntimeError: expected target dtype to be Long or Byte, but got Float

pos_weight = n_negative / n_positive balances a rare positive class, like class_weight="balanced" in scikit-learn. Never put a sigmoid before BCEWithLogitsLoss or a softmax before CrossEntropyLoss: they apply it inside, in a numerically stable way.

Optimizer Use Typical lr
torch.optim.SGD(p, lr, momentum=0.9) simple models; tuned schedules 0.01–0.1
torch.optim.Adam(p, lr) a fast default 1e-3
torch.optim.AdamW(p, lr, weight_decay=0.01) the default with decoupled weight decay 1e-3
Scheduler (torch.optim.lr_scheduler) Step call Effect
StepLR(opt, step_size=10, gamma=0.5) sched.step() per epoch halve every 10 epochs
ReduceLROnPlateau(opt, factor=0.5, patience=3) sched.step(val_loss) lower when validation stalls
OneCycleLR(opt, max_lr, total_steps) sched.step() per batch warm up, then anneal
CosineAnnealingLR(opt, T_max=epochs) sched.step() per epoch smooth decay

Build the optimizer after the model, and call sched.step() after optimizer.step().

def train_one_epoch(model, loader, loss_fn, optimizer) -> float:
model.train() # dropout on
total = 0.0
for xb, yb in loader:
optimizer.zero_grad() # 1. clear old gradients
loss = loss_fn(model(xb), yb) # 2. forward
loss.backward() # 3. gradients
optimizer.step() # 4. update
total += loss.item() * len(yb) # .item(): no graph kept
return total / len(loader.dataset)
@torch.no_grad() # no graph during evaluation
def evaluate(model, loader, loss_fn) -> float:
model.eval() # dropout off
total = sum(loss_fn(model(xb), yb).item() * len(yb) for xb, yb in loader)
return total / len(loader.dataset)
def fit(model, train_loader, valid_loader, loss_fn, optimizer, epochs=50, patience=5):
best_loss, best_state, bad = float("inf"), None, 0
for epoch in range(1, epochs + 1):
train_loss = train_one_epoch(model, train_loader, loss_fn, optimizer)
valid_loss = evaluate(model, valid_loader, loss_fn)
if valid_loss < best_loss - 1e-4: # early stopping on the validation loss
best_loss, bad = valid_loss, 0
best_state = copy.deepcopy(model.state_dict()) # a copy, not a view
else:
bad += 1
if epoch % 5 == 0 or bad == patience:
print(f"epoch {epoch:2d} train {train_loss:.4f} valid {valid_loss:.4f}")
if bad == patience:
break
model.load_state_dict(best_state) # restore the best epoch
return best_loss
torch.manual_seed(42)
model = MLP(len(features), hidden=(32, 16), dropout=0.2)
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.01)
best = fit(model, train_loader, valid_loader, nn.BCEWithLogitsLoss(), optimizer)
print("best valid loss", round(best, 4))
Output
epoch 5 train 0.4131 valid 0.4001
epoch 10 train 0.4019 valid 0.3958
epoch 15 train 0.3974 valid 0.3846
epoch 20 train 0.3849 valid 0.3829
epoch 25 train 0.3833 valid 0.3822
epoch 30 train 0.3834 valid 0.3818
epoch 34 train 0.3777 valid 0.3839
best valid loss 0.3799
from sklearn.metrics import roc_auc_score
model.eval()
with torch.no_grad():
proba = torch.sigmoid(model(valid_ds.X)).numpy() # logits -> probabilities
print(proba[:3].round(3), round(roc_auc_score(valid_ds.y.numpy(), proba), 3))
Output
[0.085 0.483 0.064] 0.812
model.train() model.eval() torch.no_grad()
dropout active off unchanged
batch norm batch statistics; updates running stats running stats unchanged
graph recorded yes yes no
use for training steps validation, prediction validation, prediction, manual updates
Tool Code Effect
dropout nn.Dropout(0.2) after each activation zeroes 20% of values in training, scales the rest by 1/0.8
weight decay AdamW(..., weight_decay=0.01) shrinks every weight a little each step
early stopping patience on the validation loss, restore the best state stops when overfitting starts
a smaller network fewer or narrower layers fewer parameters to memorize with
more data, augmentation flips, crops, noise more variety
batch norm nn.BatchNorm1d(h) before the activation stabler training; some regularization

Signs of overfitting: the training loss keeps falling while the validation loss rises. Signs of underfitting: both stay high; use a bigger network, a higher lr or more epochs.

from pathlib import Path
Path("output").mkdir(exist_ok=True)
config = {"n_features": len(features), "hidden": [32, 16], "dropout": 0.2}
torch.save({"config": config, "state_dict": model.state_dict()}, "output/churn_mlp.pt")
ckpt = torch.load("output/churn_mlp.pt", weights_only=True) # the default; explicit
cfg = ckpt["config"]
restored = MLP(cfg["n_features"], tuple(cfg["hidden"]), dropout=cfg["dropout"])
print(restored.load_state_dict(ckpt["state_dict"]))
restored.eval()
with torch.no_grad():
print(torch.equal(restored(valid_ds.X), model(valid_ds.X)))
Output
<All keys matched successfully>
True
Do Avoid
save model.state_dict() plus a config dict torch.save(model, path): pickles the class path
torch.load(path, weights_only=True) (explicit; the default since 2.6) weights_only=False on files from others
save the scaler and the feature list next to the weights a model you cannot feed
save optimizer state, epoch and RNG states to resume training resuming with a fresh optimizer
model.eval() after loading predicting with dropout on
model.load_state_dict(sd, strict=True) (default) strict=False hides missing keys
Source of variation Control
initial weights, dropout, torch.rand* torch.manual_seed(42) before building the model
DataLoader shuffling generator=torch.Generator().manual_seed(42)
NumPy and scikit-learn steps np.random.default_rng(42), random_state=42
float sums that depend on the thread count torch.set_num_threads(1)
several processes on all cores torch.set_num_threads(1) in each worker
nondeterministic kernels torch.use_deterministic_algorithms(True)
DataLoader workers worker_init_fn that seeds NumPy per worker
library versions pin torch in requirements.txt or pyproject.toml

The same seed on another machine, thread count or PyTorch version can give slightly different numbers. Compare runs with a tolerance (torch.allclose), not exact equality.

Trap Symptom Fix
float64 NumPy input RuntimeError: mat1 and mat2 must have the same dtype torch.as_tensor(arr, dtype=torch.float32)
torch.std default values differ from NumPy and StandardScaler std(correction=0)
from_numpy shares memory changing the array changes the tensor torch.tensor(arr) or .clone()
no zero_grad() the loss jumps or diverges optimizer.zero_grad() each step
sigmoid or softmax before the loss slow learning, unstable loss pass raw logits
output (n, 1), target (n,) BCE ValueError; MSE broadcasts to (n, n) with a warning squeeze(1) the output
float class labels for CrossEntropyLoss RuntimeError: expected target dtype to be Long or Byte y.long()
torch.as_tensor(series.to_numpy()) in pandas 3 UserWarning: the NumPy array is not writable torch.tensor(...) copies; or to_numpy(copy=True)
eval() forgotten predictions change between calls (dropout) model.eval() before predicting
no_grad() thought to switch modes dropout still on use eval() and no_grad() together
best weights stored as model.state_dict() the “best” weights change with training copy.deepcopy(model.state_dict())
layers kept in a plain list they do not train; missing from state_dict nn.ModuleList or nn.Sequential
optimizer built before a model rebuild the new model does not learn build the optimizer after the model
total += loss memory grows every step total += loss.item()
Conv2d on (n, H, W) channel-count error add the channel axis: x.unsqueeze(1)
torch.load(path, weights_only=False) on a file from others runs pickled code from the file keep the default safe mode; pass weights_only=True explicitly on PyTorch older than 2.6
torch.save(model, path), then torch.load(path) UnpicklingError: safe mode refuses a pickled module save and load the state_dict
tensors on different devices RuntimeError, for example Tensor for argument input is on cpu but expected on mps move the model and each batch with .to(device)
scaler fitted on all rows optimistic validation loss fit the scaler on the training rows only

Interpretability tools answer two questions: what drives a model overall (global), and why it gave one prediction (local). This page covers intrinsic explanations (coefficients), model-agnostic tools (permutation importance, partial dependence, ICE) and SHAP. The examples explain churn models fitted on data/customers.csv. The blocks share one session:

import numpy as np
import pandas as pd
import shap
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
features = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d",
"avg_session_minutes", "has_autopay", "age"]
X = customers[features].astype(float) # float: partial_dependence rejects int columns
y = customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
gbc = GradientBoostingClassifier(n_estimators=150, max_depth=3, random_state=42)
gbc.fit(X_train, y_train)
print(X.shape, round(gbc.score(X_test, y_test), 3))
Output
(5000, 7) 0.837
I want to… Use… Scope
comparable linear coefficients StandardScaler in the pipeline, then pipe[-1].coef_ global
a coefficient in original units coef / pipe[0].scale_ global
odds ratios of a logistic model np.exp(coef) global
percent change in the odds np.exp(coef) - 1 global
uncertainty of a coefficient statsmodels smf.logit(...).fit().conf_int() or a bootstrap global
a tree model’s built-in importance model.feature_importances_ global; training data; biased
what the model needs on new data permutation_importance(model, X_test, y_test, n_repeats=10, random_state=42) global
permutation importance with another metric scoring="roc_auc" global
permute raw columns through preprocessing pass the whole Pipeline and raw X_test global
check importances against noise add a random column; real features must beat it global
the average effect of one feature PartialDependenceDisplay.from_estimator(model, X, ["f"]) global
one curve per row kind="individual" or kind="both" local
compare ICE slopes kind="both", centered=True, subsample=50 local
the numbers behind a PDP partial_dependence(model, X, ["f"], kind="average") global
average over the data I pass method="brute" global
a two-feature interaction plot features=[("f1", "f2")] global
SHAP values of a tree model sv = shap.TreeExplainer(model)(X) local
SHAP values of a linear model shap.LinearExplainer(model, shap.maskers.Independent(X, max_samples=len(X))) local
check SHAP additivity np.allclose(sv.base_values + sv.values.sum(1), raw_output) local
global SHAP importance np.abs(sv.values).mean(axis=0) or shap.plots.bar(sv, show=False) global
every row and feature in one plot shap.plots.beeswarm(sv, show=False) global
explain one prediction shap.plots.waterfall(sv[i], show=False) local
SHAP against a feature value shap.plots.scatter(sv[:, "f"], color=sv, show=False) global
SHAP for a pipeline TreeExplainer(pipe[-1])(pipe[:-1].transform(X)) local
one SHAP value per original column sum the one-hot columns of each feature either
a what-if for one row change a copy of the row, call predict_proba again local
Question Method Needs labels Watch out
What does the model need to score well on new data? permutation importance yes correlated features hide each other
How much does each feature move the predictions? mean absolute SHAP no correlated features share credit
What is the average effect of a feature? PDP no averages hide opposite effects
Does the effect differ between rows? ICE, centered no impossible rows with correlated features
Why this one prediction? SHAP waterfall no log-odds for boosting classifiers
Size and sign of an effect in a linear model standardized coefficient, odds ratio — collinearity, regularization
A quick look during development feature_importances_ — training data; favors continuous features
logit = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
logit.fit(X_train, y_train)
coef = pd.Series(logit[-1].coef_[0], index=features) # log-odds per 1 SD
table = pd.DataFrame({
"coef_per_sd": coef,
"odds_ratio_per_sd": np.exp(coef),
"odds_ratio_per_unit": np.exp(coef / logit[0].scale_), # original units
})
print(table.sort_values("coef_per_sd", key=abs, ascending=False).round(3))
Output
coef_per_sd odds_ratio_per_sd odds_ratio_per_unit
tenure_months -1.133 0.322 0.945
support_tickets 0.528 1.696 1.578
monthly_charges 0.437 1.547 1.019
logins_last_30d -0.282 0.754 0.966
has_autopay -0.216 0.806 0.649
age -0.102 0.903 0.992
avg_session_minutes -0.068 0.934 0.991
Model A coefficient means Turn it into
linear regression change in y^\hat y per unit of xjx_j, the others fixed per SD: fit on scaled data; per unit: coef / scale_
logistic regression change in the log-odds per unit odds ratio np.exp(coef); percent np.exp(coef) - 1
one-hot column (drop="first") difference from the reference category name the reference category
log target change in ln⁡y\ln y per unit percent effect np.exp(coef) - 1
interaction x1:x2 the slope of x1 changes with x2 read slopes at chosen x2 values

Tenure has an odds ratio of 0.32 per SD: each extra SD of tenure (about 20 months) cuts the odds of churn to about a third, the other features fixed. Per month, the ratio is 0.945: about 5.5% lower odds. Odds are not probabilities: the change in probability depends on the starting point. Before you trust a coefficient, check correlations (X.corr() above about 0.8 makes coefficients unstable), compare models with the same penalty (C, alpha) and bootstrap the sign.

from sklearn.inspection import permutation_importance
rng = np.random.default_rng(42)
X_noise_train = X_train.assign(noise=rng.normal(size=len(X_train))) # no signal
X_noise_test = X_test.assign(noise=rng.normal(size=len(X_test)))
gbc_noise = GradientBoostingClassifier(n_estimators=150, max_depth=3, random_state=42)
gbc_noise.fit(X_noise_train, y_train)
perm = permutation_importance(gbc_noise, X_noise_test, y_test, scoring="roc_auc",
n_repeats=10, random_state=42)
imp = pd.DataFrame({
"impurity (train)": gbc_noise.feature_importances_,
"permutation (test AUC)": perm.importances_mean,
"perm_std": perm.importances_std,
}, index=X_noise_train.columns)
print(imp.sort_values("permutation (test AUC)", ascending=False).round(3))
Output
impurity (train) permutation (test AUC) perm_std
tenure_months 0.415 0.138 0.018
monthly_charges 0.144 0.033 0.006
age 0.110 0.031 0.005
support_tickets 0.089 0.026 0.007
logins_last_30d 0.113 0.026 0.004
has_autopay 0.012 0.001 0.001
noise 0.084 -0.001 0.002
avg_session_minutes 0.033 -0.002 0.002
Impurity (MDI) feature_importances_ Permutation permutation_importance
Measures split gains in the training data score drop when a column is shuffled
Data training rows held-out rows
Models trees only any fitted model or pipeline
Units shares that sum to 1 points of the metric (AUC, R²)
Cost free n_features × n_repeats predictions
Bias favors continuous and many-valued columns; noise gets credit correlated features hide each other
Can be negative no yes: the column hurts or is noise
permutation_importance argument Advice
X, y held-out data, never the training set
scoring "roc_auc", "average_precision" for rare classes; default model.score
n_repeats 5–10; report importances_std
random_state fix it for repeatable tables
max_samples lower it for large test sets

The pure-noise column gets 8% of the impurity importance, more than has_autopay, but no permutation importance. Impurity importance is computed on the training rows, where the trees split on noise.

from sklearn.inspection import partial_dependence
grid = {"tenure_months": np.array([1.0, 6.0, 12.0, 24.0, 48.0])}
pdp_brute = partial_dependence(gbc, X_test, ["tenure_months"], custom_values=grid,
method="brute") # averages over X_test
pdp_rec = partial_dependence(gbc, X_test, ["tenure_months"], custom_values=grid,
method="recursion") # trees: training data, no constant
print(pdp_brute["grid_values"][0], pdp_brute["average"][0].round(3)) # probability
print(pdp_rec["average"][0].round(3)) # raw log-odds scale for boosting classifiers
ice = partial_dependence(gbc, X_test, ["tenure_months"], custom_values=grid,
kind="individual")
print(ice["individual"][0].shape) # rows x grid points
Output
[ 1. 6. 12. 24. 48.] [0.565 0.222 0.17 0.121 0.054]
[ 1.894 0.011 -0.395 -0.835 -1.776]
(1250, 5)
method= Averages over Output for a boosting classifier Use
"auto" (default) recursion for trees with kind="average", otherwise brute depends on the choice quick plots
"brute" the X you pass predict_proba the honest average; any model; ICE
"recursion" the training data (tree structure) log-odds without the initial constant fast; trees only; levels differ

Plotting template:

import matplotlib.pyplot as plt
from sklearn.inspection import PartialDependenceDisplay
fig, axes = plt.subplots(1, 3, figsize=(12, 3.5))
PartialDependenceDisplay.from_estimator(gbc, X_test, ["tenure_months"], ax=axes[0])
PartialDependenceDisplay.from_estimator( # ICE: one line per row, plus the average
gbc, X_test, ["logins_last_30d"], kind="both", centered=True, subsample=50,
random_state=42, ax=axes[1],
)
PartialDependenceDisplay.from_estimator( # two-way interaction (contour)
gbc, X_test, [("tenure_months", "monthly_charges")], ax=axes[2],
)
fig.tight_layout()
plt.show()
Argument Values Note
features ["f"], [("f1", "f2")] a tuple draws a two-way PDP
kind "average", "individual", "both" ICE needs method="brute" (chosen automatically)
centered True every ICE line starts at 0: compare slopes
subsample int or fraction ICE lines drawn
grid_resolution, percentiles 100, (0.05, 0.95) grid between the 5th and 95th percentile
custom_values {"f": array} your own grid
categorical_features names or a mask one point per category
response_method "predict_proba", "decision_function" log-odds for classifiers

Read a PDP as “the model’s average prediction if every row had this value”. Parallel ICE lines mean no interaction; fanning or crossing lines mean the effect depends on other features.

SHAP (SHapley Additive exPlanations) splits each prediction into one contribution per feature. The parts add up exactly:

f(x)=ϕ0+∑j=1pϕj(x)f(x) = \phi_0 + \sum_{j=1}^{p} \phi_j(x)
explainer = shap.TreeExplainer(gbc)
sv = explainer(X_test) # an Explanation object
print(sv.values.shape, round(float(sv.base_values[0]), 3))
log_odds = gbc.decision_function(X_test) # the output TreeExplainer explains here
print(np.allclose(sv.base_values + sv.values.sum(axis=1), log_odds)) # additivity
row = 0
p = 1 / (1 + np.exp(-(sv.base_values[row] + sv.values[row].sum()))) # sigmoid
print(round(float(p), 4), round(float(gbc.predict_proba(X_test.iloc[[row]])[0, 1]), 4))
top = pd.Series(sv.values[row], index=features).sort_values(key=abs, ascending=False)
print(top.head(3).round(3)) # the top reasons for one customer, in log-odds
mean_abs = pd.Series(np.abs(sv.values).mean(axis=0), index=features)
print(mean_abs.sort_values(ascending=False).head(3).round(3))
Output
(1250, 7) -1.943
True
0.058 0.058
support_tickets -0.389
age -0.264
monthly_charges -0.158
dtype: float64
tenure_months 0.742
monthly_charges 0.377
support_tickets 0.338
dtype: float64

The base value −1.943 is the mean log-odds; its sigmoid (0.125) is not the churn rate (0.193). Convert only the full sum, as above.

Model Explainer Output space of the SHAP values Shape of sv.values
GradientBoostingRegressor, forest regressors TreeExplainer(model) prediction units (n, p)
GradientBoostingClassifier (binary) TreeExplainer(model) log-odds (decision_function) (n, p)
XGBoost, LightGBM classifiers TreeExplainer(model) log-odds (raw margin) (n, p)
RandomForestClassifier TreeExplainer(model) probability (n, p, n_classes): pick [:, :, 1]
linear models LinearExplainer(model, masker) the model’s raw output (n, p)
any model shap.Explainer(model.predict_proba, masker) as given; slow depends
a Pipeline TreeExplainer(pipe[-1])(pipe[:-1].transform(X)) as above encoded columns
Explanation part Holds
sv.values SHAP values
sv.base_values ϕ0\phi_0 per row: the average model output on the background
sv.data, sv.feature_names the explained rows and the column names
sv[i] one row, for waterfall
sv[:, "f"] one feature, for scatter

Plotting template (show=False, then your labels, then one plt.show()):

import matplotlib.pyplot as plt
shap.plots.beeswarm(sv, max_display=10, show=False) # every row, colored by value
plt.show()
shap.plots.bar(sv, show=False) # mean |SHAP| per feature
plt.show()
shap.plots.waterfall(sv[0], max_display=8, show=False) # one prediction
plt.title("Customer 0, log-odds of churn")
plt.show()
shap.plots.scatter(sv[:, "tenure_months"], color=sv, show=False) # dependence
plt.show()
Say Avoid
“The model’s churn score rises with support tickets” “Support tickets cause churn”
units: log-odds, probability points, AUC points a unitless “importance 0.27”
the spread over repeats, folds or seeds single numbers with false precision
original features (one-hot columns summed) payment_method_credit_card = 0
three reasons in plain words for one customer a full SHAP table
correlated groups and sparse regions silent caveats
an experiment to test an action a what-if score promised as an outcome
Trap Symptom Fix
feature_importances_ as the final answer a pure-noise column gets credit permutation importance on held-out data
permutation importance on the training set memorized noise looks important use the test or validation set
correlated features each looks unimportant when permuted alone; SHAP splits credit permute groups; report correlated features together
permuting one-hot columns one by one impossible rows (two categories at once) pass the pipeline and raw columns
integer columns in partial_dependence ValueError (scikit-learn 1.9) X.astype(float) before fitting
method="auto" on trees the PDP level differs from the mean prediction method="brute" to average over your X
a flat PDP “no effect” claimed draw ICE: opposite effects can cancel
PDP far from the data effects in regions with no rows read only between the 5th and 95th percentile
SHAP of a boosting classifier read as probability contributions do not add to predict_proba they are log-odds: sum, then apply the sigmoid
sigmoid of base_values read as the churn rate a number off from y.mean() it is the mean log-odds, not the mean probability
forest classifier SHAP shape a 3-D array select the positive class: sv[:, :, 1]
SHAP on a log target effects in log units contributions multiply on the original scale
shap plots without show=False plt.title lands on a new empty figure show=False, then plt.show()
LinearExplainer(model, X) with more than 100 rows a subsampling message on the output shap.maskers.Independent(X, max_samples=len(X))
explanations read causally wrong business decisions explanations describe the model; test actions with experiments
explaining a weak model confident stories about noise check the test score before explaining

A model in production is a program that other programs call. It must load the right model, reject bad input, answer fast, and warn you when the world changes. This page covers the project layout, saving a model with its metadata, loading it safely, serving it with FastAPI and pydantic, testing the service, detecting drift, tracking experiments with MLflow and what to monitor. The same FastAPI, pydantic and testing patterns apply to any web API. The examples use data/customers.csv. The blocks share one session:

import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
CATEGORICAL = ["plan", "contract"]
NUMERIC = ["age", "tenure_months", "monthly_charges", "support_tickets"]
FEATURES = CATEGORICAL + NUMERIC
customers = pd.read_csv("data/customers.csv")
train, test = train_test_split(customers, test_size=0.2,
stratify=customers["churned"], random_state=42)
pipeline = Pipeline([
("prep", ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore"), CATEGORICAL),
("num", StandardScaler(), NUMERIC),
])),
("model", LogisticRegression(max_iter=1000)),
]).fit(train[FEATURES], train["churned"])
auc = roc_auc_score(test["churned"], pipeline.predict_proba(test[FEATURES])[:, 1])
print(f"test ROC-AUC {auc:.3f}")
Output
test ROC-AUC 0.799
I want to… Use… Notes
repeatable training random_state=42 on every random step splits, models, CV
pin the environment uv lock or uv pip freeze > requirements.txt exact versions
record library versions importlib.metadata.version("scikit-learn") into the metadata
fingerprint a file hashlib.sha256(path.read_bytes()).hexdigest() data and model files
a split that stays stable as data grows zlib.crc32(customer_id.encode()) % 100 < 20 not hash()
read a config file with open("config/train.toml", "rb") as f: cfg = tomllib.load(f) binary mode
save a model with metadata joblib.dump({"pipeline": p, "metadata": m}, path) + a JSON sidecar
check a model before loading read the JSON sidecar: versions, features, SHA-256 before joblib.load; a trusted copy of the hash stops tampering
load a saved model joblib.load(path) only files you created
a JSON API app = FastAPI(), @app.post("/predict")
validate a request body a pydantic BaseModel as the parameter type 422 on failure
a number in a range Field(ge=18, le=100) gt, lt for strict bounds
fixed categories only Literal["basic", "standard", "premium"] unknown values → 422
reject unknown fields model_config = ConfigDict(extra="forbid") catches typos
reject inf and NaN ConfigDict(allow_inf_nan=False)
no type conversion ConfigDict(strict=True) "34" is an error
load the model once at start-up FastAPI(lifespan=lifespan)
“not ready” / “failed” answers HTTPException(status_code=503), 500 generic detail
run the API uvicorn app:app --reload development
test the API without a server with TestClient(app) as client: needs httpx2
a request in a test client.post("/predict", json=payload) .status_code, .json()
measure a shift in a feature PSI on reference deciles > 0.25 = major
test a continuous shift scipy.stats.ks_2samp(ref, cur) not for 0/1 or categories
a categorical shift PSI on category shares, or chi2_contingency
a local experiment store mlflow.set_tracking_uri("sqlite:///mlflow.db") not file:./mlruns
log a run with mlflow.start_run(): mlflow.log_params(...); mlflow.log_metrics(...)
compare runs mlflow.search_runs(order_by=["metrics.auc DESC"]) a DataFrame
open the tracking UI mlflow ui --backend-store-uri sqlite:///mlflow.db Terminal
Project layout
churn-service/
├── pyproject.toml # dependencies, pinned by uv.lock
├── uv.lock
├── config/train.toml # seed, paths, hyperparameters
├── data/raw/ # read-only snapshots (not in git when large)
├── models/ # model bundles + JSON sidecars (not in git)
├── notebooks/ # exploration only
├── src/churn/
│ ├── features.py # column lists, build_pipeline()
│ ├── train.py # python -m churn.train: data -> models/
│ ├── bundle.py # save_bundle(), load_bundle()
│ └── api.py # FastAPI app
└── tests/
├── test_bundle.py
└── test_api.py # TestClient
Rule Why
one module defines the features and the pipeline training and serving cannot drift apart
training is a script, not a notebook one command, top to bottom, repeatable
configs in a file, not in code change settings without changing code
models and data snapshots out of git large binary files; store them elsewhere with their hash
tests for the bundle and the API catch broken models before users do
Reproducibility source Fix Record
random steps seed each one seed
library versions lock file sklearn_version, …
data snapshot + SHA-256 data_sha256
test rows hash split by a permanent id the split rule
code and settings git commit + config file git_commit, model_version
import hashlib
import json
from pathlib import Path
import joblib
import sklearn
def file_sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def save_bundle(pipeline, metadata: dict, path: Path) -> None:
"""One joblib file (pipeline + metadata) and a JSON sidecar with its hash."""
path.parent.mkdir(parents=True, exist_ok=True)
joblib.dump({"pipeline": pipeline, "metadata": metadata}, path)
sidecar = metadata | {"bundle_sha256": file_sha256(path)}
path.with_suffix(".json").write_text(json.dumps(sidecar, indent=2))
metadata = {
"model_version": "1.0.0",
"trained_at": "2025-01-06", # write the real date in train.py
"sklearn_version": sklearn.__version__,
"features": FEATURES,
"metrics": {"test_roc_auc": round(auc, 4)},
"threshold": 0.5,
}
MODEL_PATH = Path("models/churn.joblib")
save_bundle(pipeline, metadata, MODEL_PATH)
sidecar = json.loads(MODEL_PATH.with_suffix(".json").read_text())
print(sorted(sidecar)[:4], len(sidecar))
Output
['bundle_sha256', 'features', 'metrics', 'model_version'] 7
Metadata field Why
model_version logs, API responses and bug reports refer to it
trained_at the age of the model
data_sha256 which data trained it
sklearn_version (and pandas, NumPy) a pickle needs the same versions
features the exact inputs, in order
metrics the baseline for monitoring
threshold how a probability becomes an action

A joblib or pickle file can run code when it loads. Check what you can before joblib.load, using only the plain JSON sidecar. The hash detects a corrupted, replaced or accidentally changed file. It does not stop an attacker who can also rewrite the sidecar next to it. Against tampering, keep the expected hash where they cannot write (a model registry, the deploy config in git, a signed manifest), or share models as skops or ONNX files.

class ModelLoadError(RuntimeError):
"""The saved bundle cannot be used safely."""
def load_bundle(path: Path) -> dict:
sidecar = path.with_suffix(".json")
if not path.exists() or not sidecar.exists():
raise ModelLoadError(f"{path.name} or its sidecar is missing")
meta = json.loads(sidecar.read_text()) # JSON cannot run code
if meta["sklearn_version"] != sklearn.__version__:
raise ModelLoadError(f"saved with scikit-learn {meta['sklearn_version']}")
if meta["features"] != FEATURES:
raise ModelLoadError("the feature list changed")
if file_sha256(path) != meta["bundle_sha256"]:
raise ModelLoadError(f"{path.name} changed since it was saved")
return joblib.load(path) # only after every check
bundle = load_bundle(MODEL_PATH)
print(bundle["metadata"]["model_version"], type(bundle["pipeline"]).__name__)
Output
1.0.0 Pipeline

A changed file (with an unchanged sidecar) is refused before it is unpickled:

Path("models/copy.joblib").write_bytes(MODEL_PATH.read_bytes() + b"\x00")
Path("models/copy.json").write_text(MODEL_PATH.with_suffix(".json").read_text())
load_bundle(Path("models/copy.joblib"))
Output
ModelLoadError: copy.joblib changed since it was saved
Format Safe to load from others Use
joblib / pickle no: can run code your own models, same versions
skops.io with an explicit list of trusted types sharing scikit-learn models
ONNX yes (data only) fast, cross-language serving
torch.save(state_dict) + torch.load(weights_only=True) mostly: tensors and plain types only PyTorch weights
JSON sidecar yes metadata you check first
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Literal
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, ConfigDict, Field
models: dict[str, dict] = {}
class Customer(BaseModel):
"""The request body. Every field is checked before the model runs."""
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
plan: Literal["basic", "standard", "premium"]
contract: Literal["month-to-month", "one-year", "two-year"]
age: int = Field(ge=18, le=100)
tenure_months: int = Field(ge=0, le=600)
monthly_charges: float = Field(gt=0, le=1000)
support_tickets: int = Field(default=0, ge=0, le=100)
class Prediction(BaseModel):
churn_probability: float
will_churn: bool
model_version: str
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
models["churn"] = load_bundle(MODEL_PATH) # once, at start-up
yield
models.clear()
app = FastAPI(title="Churn API", lifespan=lifespan)
@app.get("/health")
def health() -> dict[str, str]:
if "churn" not in models:
raise HTTPException(status_code=503, detail="model not loaded")
version = models["churn"]["metadata"]["model_version"]
return {"status": "ok", "model_version": version}
@app.post("/predict")
def predict(customer: Customer) -> Prediction:
if "churn" not in models:
raise HTTPException(status_code=503, detail="model not loaded")
bundle = models["churn"]
row = pd.DataFrame([customer.model_dump()], columns=FEATURES) # fixed column order
proba = float(bundle["pipeline"].predict_proba(row)[0, 1])
return Prediction(churn_probability=round(proba, 4),
will_churn=proba >= bundle["metadata"]["threshold"],
model_version=bundle["metadata"]["model_version"])
Terminal
uvicorn app:app --reload # development server on http://127.0.0.1:8000
curl -X POST http://127.0.0.1:8000/predict \
-H "Content-Type: application/json" -d @customer.json # body from a JSON file

Open http://127.0.0.1:8000/docs for the interactive schema that FastAPI builds from the pydantic models.

pydantic tool Meaning
x: int type check with lax conversion: "34" → 34
Field(ge=0, le=120) / Field(gt=0, lt=1) inclusive / exclusive range
Field(min_length=1, max_length=100) length of a string or list
Field(pattern=r"^C\d{5}$") a regex for strings
Literal["a", "b"] exact allowed values
x: float | None = None optional field
ConfigDict(extra="forbid") unknown fields are errors
ConfigDict(strict=True) no conversions
ConfigDict(allow_inf_nan=False) reject inf and NaN
Model.model_validate(d), obj.model_dump() dict → model, model → dict
Status Meaning in an ML API
200 prediction returned
404 unknown resource
422 the body failed validation; detail lists every error
500 the model or the code failed; log the cause, send a generic detail
503 not ready: the model is not loaded

TestClient calls the app in-process, without a server. In the course environment it runs on the httpx2 package; without it, importing TestClient warns.

from fastapi.testclient import TestClient
payload = {"plan": "basic", "contract": "month-to-month", "age": 30,
"tenure_months": 2, "monthly_charges": 70.0, "support_tickets": 3}
loyal = payload | {"contract": "two-year", "tenure_months": 60, "support_tickets": 0}
with TestClient(app) as client: # "with" runs the lifespan: the model loads
print(client.get("/health").json())
risky = client.post("/predict", json=payload)
safe = client.post("/predict", json=loyal)
print(risky.status_code, risky.json())
print(risky.json()["churn_probability"] > safe.json()["churn_probability"])
bad = client.post("/predict", json=payload | {"age": 16, "plan": "gold",
"promo": "X"})
print(bad.status_code, [(e["loc"][-1], e["type"]) for e in bad.json()["detail"]])
saved = models.pop("churn") # simulate a model that failed to load
print(client.post("/predict", json=payload).json())
models["churn"] = saved
Output
{'status': 'ok', 'model_version': '1.0.0'}
200 {'churn_probability': 0.6286, 'will_churn': True, 'model_version': '1.0.0'}
True
422 [('plan', 'literal_error'), ('age', 'greater_than_equal'), ('promo', 'extra_forbidden')]
{'detail': 'model not loaded'}
tests/test_api.py
import pytest
from fastapi.testclient import TestClient
from churn import api
VALID = {"plan": "basic", "contract": "month-to-month", "age": 30,
"tenure_months": 2, "monthly_charges": 70.0, "support_tickets": 3}
RISKY = VALID
LOYAL = VALID | {"contract": "two-year", "tenure_months": 60, "support_tickets": 0}
@pytest.fixture(scope="module")
def client():
with TestClient(api.app) as c: # runs the lifespan once for the module
yield c
def test_health(client):
assert client.get("/health").json()["status"] == "ok"
@pytest.mark.parametrize("field, value", [("age", 16), ("plan", "gold"),
("monthly_charges", -5)])
def test_invalid_input_is_422(client, field, value):
body = VALID | {field: value}
assert client.post("/predict", json=body).status_code == 422
def test_risky_scores_higher_than_loyal(client): # an ordering, not exact numbers
risky = client.post("/predict", json=RISKY).json()["churn_probability"]
loyal = client.post("/predict", json=LOYAL).json()["churn_probability"]
assert risky > loyal
def test_missing_model_is_503(client, monkeypatch):
monkeypatch.delitem(api.models, "churn") # restored after the test
assert client.post("/predict", json=VALID).status_code == 503
Test Asserts
health 200 and the model version
valid input 200, a probability in [0, 1]
invalid input 422 for each bad field
ordering risky profiles score higher than loyal ones
model missing 503, not a crash
bundle checks changed file or other versions → ModelLoadError

Do not assert exact probabilities: they change with every retraining.

PSI=∑i=1B(ci−ri)ln⁡ciriD=max⁡x∣Fref(x)−Fcur(x)∣\mathrm{PSI} = \sum_{i=1}^{B} (c_i - r_i)\ln\frac{c_i}{r_i} \qquad D = \max_x \lvert F_\text{ref}(x) - F_\text{cur}(x) \rvert

rir_i and cic_i are the shares of the reference and the current data in bin ii. The bins are the deciles of the reference data. DD is the Kolmogorov–Smirnov (KS) statistic: the largest gap between the two cumulative distributions.

from scipy.stats import ks_2samp
def psi(reference, current, bins: int = 10) -> float:
"""Population stability index on the deciles of the reference data."""
reference, current = np.asarray(reference), np.asarray(current)
inner = np.unique(np.quantile(reference, np.linspace(0, 1, bins + 1))[1:-1])
r = np.bincount(np.searchsorted(inner, reference, side="right"),
minlength=len(inner) + 1) / len(reference)
c = np.bincount(np.searchsorted(inner, current, side="right"),
minlength=len(inner) + 1) / len(current)
r, c = np.clip(r, 1e-4, None), np.clip(c, 1e-4, None) # avoid log(0)
return float(np.sum((c - r) * np.log(c / r)))
signup = pd.to_datetime(customers["signup_date"])
reference = customers[signup < "2023-01-01"] # older customers
current = customers[signup >= "2024-01-01"] # this year's sign-ups
for col in ["age", "monthly_charges", "tenure_months"]:
ks = ks_2samp(reference[col], current[col])
print(f"{col:<16} PSI {psi(reference[col], current[col]):6.3f} "
f"KS D {ks.statistic:.3f} p {ks.pvalue:.2g}")
Output
age PSI 0.015 KS D 0.021 p 0.77
monthly_charges PSI 0.035 KS D 0.038 p 0.12
tenure_months PSI 8.663 KS D 1.000 p 0

Age and charges are stable. Tenure shows a huge shift, but by construction: this year’s sign-ups cannot have long tenure. A feature tied to time drifts on purpose; compare like with like, or monitor it against the same cohort last year.

PSI Reading Action
below 0.1 stable none
0.1–0.25 moderate check the feature and its source
above 0.25 major investigate; consider retraining
Drift kind What changes Needs labels Check
data drift (covariate shift) input distributions no PSI, KS per feature
prediction drift score distribution, flag rate no PSI on the scores
prior (label) shift class shares yes the positive rate
concept drift the input–target relation yes the metric on new labels
track.py (MLflow 3.18)
import logging
import os
import mlflow
import mlflow.sklearn
from mlflow.models import infer_signature
logging.getLogger("mlflow").setLevel(logging.WARNING) # hide INFO lines
os.environ["MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR"] = "false" # no tqdm on stderr
mlflow.set_tracking_uri("sqlite:///mlflow.db") # file:./mlruns raises in 3.18
mlflow.set_experiment("churn-baseline")
for C in [0.1, 1.0]:
with mlflow.start_run(run_name=f"logreg-C{C}"): # one run per setting
model = build_pipeline(C=C).fit(X_train, y_train)
mlflow.log_params({"C": C, "seed": 42})
mlflow.log_metrics({"cv_auc_mean": cv_auc(model)})
mlflow.set_tag("data_sha256", data_hash)
signature = infer_signature(X_train, model.predict_proba(X_train))
mlflow.sklearn.log_model(
model, name="model", signature=signature,
pyfunc_predict_fn="predict_proba", # generic loader returns probabilities
skops_trusted_types=["numpy.dtype"], # MLflow 3 saves with skops
pip_requirements=[f"scikit-learn=={sklearn.__version__}"],
)
runs = mlflow.search_runs(experiment_names=["churn-baseline"],
order_by=["metrics.cv_auc_mean DESC"])
best = mlflow.sklearn.load_model(f"runs:/{runs.iloc[0]['run_id']}/model")
Call Does
mlflow.set_tracking_uri("sqlite:///mlflow.db") a local database file in the current folder
mlflow.set_experiment(name) create or select an experiment
with mlflow.start_run(run_name=...) one run; closes itself
log_params, log_metrics, set_tag settings (stored as text), results, labels
log_artifact(path) any file: a chart, a report
mlflow.sklearn.log_model(...) the model with signature and requirements
mlflow.search_runs(...) runs as a DataFrame: params.*, metrics.*, tags.*
mlflow.sklearn.load_model("runs:/<id>/model") the original pipeline
mlflow.pyfunc.load_model(uri) a generic predict() that checks the signature
mlflow ui --backend-store-uri sqlite:///mlflow.db the web UI (Terminal)

Log cross-validation scores for model selection. Touch the test set once, for the final model.

  1. Service: request count, error rate (5xx), latency (p50, p95). Alert: p95 above your budget.
  2. Input quality: 422 rate, missing values, unknown categories, values at the edge of the allowed ranges. Alert: more than 2% rejected.
  3. Data drift: PSI per feature against the training data, every day or week. Alert: any PSI above 0.25.
  4. Prediction drift: PSI of the scores, the share of positive decisions. Alert: the flag rate moves by a third.
  5. Performance: the training metric (ROC-AUC, recall) on new labels when they arrive. Alert: a drop larger than the CV spread.
  6. Traceability: log the model version, the input and the output of every prediction (without personal data you do not need).
  7. Retraining: a written rule (schedule or alert), the same training script, a comparison with the current model before the switch.
  8. Rollback: keep the previous bundle and switch back with one change.
Trap Symptom Fix
hash("C00001") for a split a different split in every process zlib.crc32 or hashlib
random split with a seed the test set changes when rows are added hash split by a permanent id
joblib.load on files from others arbitrary code runs load only your files; check the hash first
other scikit-learn version only an InconsistentVersionWarning; predictions may change or fail check the version in the sidecar and refuse
checks after joblib.load too late for a malicious file check the hash against a trusted record before loading
expected hash stored next to the model an attacker who replaces the model rewrites the sidecar too keep the hash in a registry, the deploy config or a signed manifest
no Literal on categories an unknown category becomes an all-zero one-hot row Literal[...] → 422
no extra="forbid" a misspelled optional field is ignored silently ConfigDict(extra="forbid")
lax mode "34" → 34, "yes" → True strict=True where that matters
float fields by default NaN, Infinity, 1e308 accepted allow_inf_nan=False and an upper bound
TestClient(app) without with the lifespan never runs: 503 with TestClient(app) as client:
TestClient without httpx2 a warning on import install the pinned requirements
relative paths in uvicorn app:app the model file is not found build paths from Path(__file__).parent
leaking stack traces internal details in 500 responses log the error; send a generic detail
KS test on 0/1 or few values misleading p-values PSI on the values, or a chi-square test
KS on large samples tiny, harmless shifts are “significant” decide on the PSI or the size of D
PSI bins from the current data drift hidden bins from the reference data
file:./mlruns in MLflow 3.18 MlflowException sqlite:///mlflow.db
MLflow logs and progress bars INFO lines and tqdm bars on stderr mlflow logger to WARNING, MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR=false
params.* from search_runs strings, not numbers runs["params.C"].astype(float)
choosing runs by the test score an optimistic final score select on CV; test once

This guide picks the container for a job: built-in collections, the collections and heapq tools, record types, NumPy arrays and DataFrames. It gives the big-O cost of common operations and the memory per element. The rules apply to any Python program, not only to data work.

flowchart TD
    A{"Many numbers,<br/>math on whole columns?"} -->|yes| B{"Named columns,<br/>mixed types?"}
    B -->|yes| DF["DataFrame<br/>pandas / Polars"]
    B -->|no| NP["NumPy array"]
    A -->|no| C{"Find values by a key?"}
    C -->|yes| D{"Count or group?"}
    D -->|count| CT["Counter"]
    D -->|group| DD["defaultdict(list)"]
    D -->|neither| DI["dict"]
    C -->|no| E{"Only membership<br/>or uniqueness?"}
    E -->|yes| S["set / frozenset"]
    E -->|no| F{"One record with<br/>named fields?"}
    F -->|yes| R["dataclass / NamedTuple"]
    F -->|no| G{"Add or take at both ends,<br/>or keep the last n?"}
    G -->|yes| DQ["deque"]
    G -->|no| H{"Always need the<br/>smallest or the top k?"}
    H -->|yes| HQ["heapq on a list"]
    H -->|no| L["list<br/>tuple if it never changes"]
I want to… Use… Example
keep items in order, change them later list orders.append(order)
a fixed sequence, a function’s several results tuple return low, high
a key made of several values tuple as a dict key totals[("S01", "2024-03")]
find a value by its id dict prices["P001"]
a default for a missing key d.get(k, default) stock.get("P099", 0)
test “have I seen this?” fast set if order_id in seen:
unique values in first-seen order dict.fromkeys(items) list(dict.fromkeys(ids))
shared and different members set operators &, -, ^ bought_a & bought_b
a set as a dict key or set member frozenset {frozenset({"tea", "milk"}): 3}
count items Counter Counter(words).most_common(3)
group items into lists by key defaultdict(list) by_store[s].append(row)
sum values per key defaultdict(float) or Counter revenue[region] += amount
a FIFO queue deque + popleft() queue.popleft()
a stack (LIFO) list + append() / pop() stack.pop()
keep only the last n items deque(maxlen=n) deque(maxlen=7)
always take the smallest next heapq.heappush / heappop a task scheduler
top k of many items heapq.nlargest(k, it, key=...) top 3 orders
insert into a list that stays sorted bisect.insort insort(times, t)
find a position in sorted data bisect.bisect_left the first reading after t
a record with named fields and defaults @dataclass Order(id="O1", qty=2)
a small, immutable record you can unpack NamedTuple lat, lon = point
millions of small records @dataclass(slots=True) or a DataFrame
type hints for JSON dicts TypedDict class Payload(TypedDict): id: int
a read-only view of a dict types.MappingProxyType(d) expose config safely
layered settings (CLI over env over defaults) ChainMap(cli, env, defaults) first match wins
fast math on many numbers NumPy array prices * 1.2
a table with named, typed columns pandas or Polars DataFrame df.groupby("region")["revenue"].sum()
compact numbers without NumPy array.array("d", values) 8 bytes per float
bytes you change in place bytearray network buffers
Structure Ordered Mutable Hashable Duplicates Find by Best for
list yes yes no yes position sequences, stacks, sort and slice
tuple yes no if its items are yes position fixed records, dict keys, return values
dict insertion order yes no unique keys key lookups, mappings, JSON
set no yes no no value membership, uniqueness, set algebra
frozenset no no yes no value sets as keys
deque yes yes no yes ends queues, sliding windows
heapq list heap order only yes no yes smallest priority queues, top k
Counter insertion order yes no unique keys key counts, histograms of values
defaultdict insertion order yes no unique keys key grouping, accumulating
@dataclass fields in order yes (or frozen) if frozen=True — attribute records with defaults and methods
NamedTuple yes no if its items are — attribute or position small immutable records
NumPy ndarray yes values yes, size no no yes position, mask numeric vectors and matrices
pandas DataFrame yes yes no yes label, mask mixed-type tables, groupby, joins
Polars DataFrame yes methods return new frames no yes expression fast tables, lazy pipelines

Average case. nn is the size of the container, kk the number of items asked for.

Operation list dict / set deque heapq sorted list + bisect NumPy array
get item i O(1)O(1) — O(n)O(n) in the middle, O(1)O(1) at the ends O(1)O(1) (only h[0] is meaningful) O(1)O(1) O(1)O(1)
x in c O(n)O(n) O(1)O(1) O(n)O(n) O(n)O(n) O(log⁡n)O(\log n) with bisect O(n)O(n), vectorized
add at the end O(1)O(1) amortized O(1)O(1) O(1)O(1) O(log⁡n)O(\log n) push O(n)O(n) insort O(n)O(n): copies the array
add or remove at the front O(n)O(n) — O(1)O(1) — O(n)O(n) O(n)O(n)
remove a given value O(n)O(n) O(1)O(1) O(n)O(n) O(n)O(n) O(n)O(n) O(n)O(n) (new array)
smallest item O(n)O(n) O(n)O(n) O(n)O(n) O(1)O(1) peek, O(log⁡n)O(\log n) pop O(1)O(1) O(n)O(n), vectorized
top k O(nlog⁡k)O(n \log k) with nlargest O(nlog⁡k)O(n \log k) O(nlog⁡k)O(n \log k) O(klog⁡n)O(k \log n) O(k)O(k) O(n)O(n) with np.partition
sort O(nlog⁡n)O(n \log n) via sorted() via sorted() O(nlog⁡n)O(n \log n) already sorted O(nlog⁡n)O(n \log n)
sum of all values O(n)O(n), Python loop O(n)O(n) O(n)O(n) O(n)O(n) O(n)O(n) O(n)O(n) in C: 10–100× faster

“Amortized” means the average over many calls: a list sometimes grows its storage, and that one call is slower. Dict and set operations are O(1)O(1) on average and degrade only when many keys hash to the same slot.

A DataFrame follows its columns: a column is an array, so whole-column math is vectorized and fast. Row-by-row loops (iterrows, apply(axis=1)) are Python loops, often 100× slower than a column expression. Appending one row copies the frame: collect rows in a list, then build the frame once.

import timeit
ids = [f"C{n:05d}" for n in range(1, 5001)]
id_set = set(ids)
t_list = timeit.timeit('"C05000" in ids', globals=globals(), number=200)
t_set = timeit.timeit('"C05000" in id_set', globals=globals(), number=200)
print("set lookup at least 50x faster:", t_set * 50 < t_list)
Output
set lookup at least 50x faster: True
import sys
from collections import deque
import numpy as np
items = list(range(1_000))
containers = {
"list": items,
"tuple": tuple(items),
"set": set(items),
"dict": dict.fromkeys(items),
"deque": deque(items),
}
for name, c in containers.items():
print(f"{name:<6} {sys.getsizeof(c):>7,} bytes") # the container only
print(f"ints {sum(sys.getsizeof(i) for i in items):>7,} bytes") # the int objects
print(f"array {np.arange(1_000).nbytes:>7,} bytes") # raw int64 values, no objects
Output
list 8,056 bytes
tuple 8,040 bytes
set 32,984 bytes
dict 36,952 bytes
deque 8,680 bytes
ints 28,000 bytes
array 8,000 bytes
Structure Bytes per element (64-bit CPython) Notes
list, tuple 8 (a pointer) + the object a tuple is a little smaller and never over-allocates
int, float object 28 and 24 each boxed number is a full object
set, dict about 30–60 + the objects a hash table keeps empty slots for speed
deque about 8 + the objects blocks of 64 pointers
instance of a plain class about 100 with its attribute storage measure: CPython 3.11+ stores attributes compactly
@dataclass(slots=True) instance 48 for two fields (sys.getsizeof, CPython 3.13) no per-object __dict__; 8 more per field
NumPy int64 / float64 8, no object per value int32, float32 halve it
pandas numeric column 8 + the index df.memory_usage(deep=True)
pandas str column the text itself (Arrow storage) category dtype for few distinct values
Polars column Arrow buffers: 8 per number, text in one buffer df.estimated_size("mb")

sys.getsizeof is shallow: it counts the container, not the objects it points to. For a whole structure, use tracemalloc or df.memory_usage(deep=True).

Tool Import Key methods Use it for
deque from collections import deque append, appendleft, pop, popleft, rotate, maxlen= queues, BFS, last-n windows
Counter from collections import Counter most_common(k), update, total(), +, -, & counts, top values, multisets
defaultdict from collections import defaultdict defaultdict(list), (int), (set) grouping, accumulating
OrderedDict from collections import OrderedDict move_to_end, popitem(last=False) LRU caches; order-sensitive ==
ChainMap from collections import ChainMap new_child, .maps layered lookups, scopes
heapq import heapq heappush, heappop, heapify, nlargest, nsmallest, merge priority queues, top k, merging sorted streams
bisect import bisect bisect_left, bisect_right, insort sorted lists, bands and thresholds
array import array array("d", values) compact numbers without NumPy
Need Use Why
quick script, keys not known in advance dict no class needed
JSON in, JSON out dict + TypedDict hints stays a dict; the type checker checks keys
a small result that callers unpack NamedTuple name, score = best
defaults, methods, light validation @dataclass readable, typed, standard library
must not change, used as a key @dataclass(frozen=True) or NamedTuple hashable
millions of records a DataFrame, or @dataclass(slots=True) columns beat objects
untrusted input to validate and convert pydantic BaseModel coercion and clear errors

Details for each record type are on the data containers page.

Data Choose Why not the others
a few hundred mixed values list / dict NumPy and pandas have a start-up and per-call cost
one numeric vector or a matrix NumPy array a list of floats is about 4× larger and 10–100× slower to sum
an image, a tensor NumPy array (PyTorch tensor for training) n-dimensional, one dtype
a table of mixed column types pandas or Polars DataFrame a NumPy array has one dtype for all cells
rows of records from an API list[dict], then pd.DataFrame(rows) build the frame once, not row by row
a table larger than memory Polars lazy with the streaming engine, or DuckDB pandas loads everything; a plain collect() loads the result too

See pandas vs Polars vs SQL for the table libraries.

The scenarios use the orders in data/sales.csv, read with the standard library:

import csv
import heapq
from collections import Counter, defaultdict
with open("data/sales.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f)) # list[dict[str, str]]
print(len(rows), rows[0]["order_id"], rows[0]["customer_id"])
Output
20228 O000001 C00618

Unique customers in first-seen order. A set loses the order. dict.fromkeys keeps it.

customers = list(dict.fromkeys(r["customer_id"] for r in rows))
print(len(customers), customers[:3])
Output
3254 ['C00618', 'C00971', 'C01140']

The best-selling categories. Counter counts in one pass and sorts the result.

units = Counter()
for r in rows:
units[r["category"]] += int(r["quantity"])
print(units.most_common(3))
Output
[('Clothing', 6522), ('Beauty', 5491), ('Sports', 4547)]

All orders of each store. defaultdict(list) creates the empty list on first use.

by_store: defaultdict[str, list[float]] = defaultdict(list)
for r in rows:
by_store[r["store_id"]].append(float(r["revenue"]))
print(len(by_store), round(sum(by_store["S01"]), 2))
Output
12 406532.46

A total per compound key. A tuple of values is a valid dict key; a list is not.

monthly: defaultdict[tuple[str, str], float] = defaultdict(float)
for r in rows:
monthly[(r["region"], r["order_date"][:7])] += float(r["revenue"])
print(round(monthly[("North", "2024-12")], 2))
Output
78630.15

The three largest order lines. heapq.nlargest keeps only k items in memory: O(nlog⁡k)O(n \log k), not a full sort.

top = heapq.nlargest(3, rows, key=lambda r: float(r["revenue"]))
print([(r["order_id"], r["revenue"]) for r in top])
Output
[('O001531', '5196.0'), ('O006934', '4596.0'), ('O011849', '4596.0')]

A rolling window of the last 3 values. deque(maxlen=3) drops the oldest item on each append.

from collections import deque
window = deque(maxlen=3)
for value in [12.0, 15.0, 11.0, 18.0, 20.0]:
window.append(value)
print(list(window), round(sum(window) / len(window), 2))
Output
[12.0] 12.0
[12.0, 15.0] 13.5
[12.0, 15.0, 11.0] 12.67
[15.0, 11.0, 18.0] 14.67
[11.0, 18.0, 20.0] 16.33

A priority queue. A counter in the tuple breaks ties, so Python never compares the payloads.

from itertools import count
tasks: list[tuple[int, int, str]] = []
order = count()
for priority, name in [(2, "email report"), (1, "restart api"), (2, "rotate logs")]:
heapq.heappush(tasks, (priority, next(order), name)) # the lowest number pops first
print([heapq.heappop(tasks)[2] for _ in range(len(tasks))])
Output
['restart api', 'email report', 'rotate logs']
Trap Symptom Fix
x in big_list inside a loop the loop is quadratic and slow build a set once, before the loop
list.pop(0) or insert(0, x) as a queue slow on long lists deque.popleft(), appendleft()
a list, dict or set as a dict key TypeError: unhashable type: 'list' a tuple or a frozenset
[[0] * 3] * 3 changing one row changes all rows [[0] * 3 for _ in range(3)]
b = a changes to b show in a a.copy(); copy.deepcopy(a) for nested data
{} for an empty set you get a dict set()
printing a set of strings the order changes between runs sorted(s)
d[k] on a missing key KeyError d.get(k), defaultdict, or k in d first
defaultdict read with d[k] the read inserts an empty value d.get(k) or k in d for reads
a printed heap list it looks unsorted only h[0] is the smallest; pop, or sorted(h)
(priority, dict) on a heap TypeError when two priorities are equal (priority, counter, item)
bisect on unsorted data a wrong position, no error sort first
a Counter with negative counts most_common shows odd items +c drops counts ≤ 0
deque[i] in the middle slow random access a list
growing a NumPy array with np.append in a loop each call copies: quadratic collect in a list, call np.array once
pd.concat one row at a time slow, quadratic build a list[dict], then one DataFrame
sys.getsizeof(container) as the total size far too small tracemalloc, df.memory_usage(deep=True)
a frozen dataclass with a list field the list still changes; hash() fails store a tuple
a NamedTuple compared with a tuple Point(1, 2) == (1, 2) is True a frozen dataclass when the type matters

Start from the question, not from the chart type. This guide maps each kind of question to a chart, gives the call in Matplotlib, Seaborn and Plotly Express, and lists the traps that make a chart lie. The examples use data/customers.csv, data/ab_test.csv and data/sales.csv.

flowchart TD
    Q{"What is the question?"} -->|"shape of one variable"| D{"Fewer than<br/>50 values?"}
    D -->|yes| D1["strip plot"]
    D -->|no| D2["histogram / ECDF"]
    Q -->|"compare groups"| G{"A number or a<br/>distribution per group?"}
    G -->|number| G1["sorted bar,<br/>CI for a rate"]
    G -->|distribution| G2["box / violin /<br/>ECDF per group"]
    Q -->|"two numbers"| R{"More than<br/>5,000 points?"}
    R -->|yes| R1["hexbin / 2-D histogram"]
    R -->|no| R2["scatter + trend line"]
    Q -->|"change over time"| T{"More than<br/>about 5 series?"}
    T -->|yes| T1["small multiples"]
    T -->|no| T2["line chart"]
    Q -->|"parts of a whole"| P["sorted bar of shares,<br/>100% stacked bar"]
    Q -->|"many variables"| M["correlation heatmap,<br/>pairplot of 3–5 columns"]
I want to… Use… Call
show the shape of one numeric column histogram sns.histplot(data=df, x="price")
show a skewed column (money, counts) histogram on a log axis sns.histplot(data=df, x="price", log_scale=True)
show percentiles you can read off ECDF sns.ecdfplot(data=df, x="time_on_page_s")
show a smooth density KDE (check with a histogram) sns.kdeplot(data=df, x="price", cut=0)
show the few values of a small sample strip or swarm plot sns.stripplot(data=df, x="group", y="score")
show distributions of several groups box, violin or ECDF with hue sns.boxplot(data=df, x="plan", y="charges")
show group histograms of different sizes density per group sns.histplot(..., hue="g", stat="density", common_norm=False)
show a number per category sorted horizontal bars ax.barh(s.index, s.values) after s.sort_values()
show a rate per group with uncertainty bars or points with a CI sns.barplot(..., errorbar=("ci", 95), seed=42)
show a change between two moments slope chart or dumbbell ax.plot([0, 1], [before, after]) per item
show two numeric columns scatter plot sns.scatterplot(data=df, x="sqft", y="price", alpha=0.4)
show a trend through a scatter regression or LOWESS line sns.regplot(..., lowess=True)
show thousands of points hexbin or 2-D histogram ax.hexbin(x, y, gridsize=40, mincnt=1)
show a third variable on a scatter color or size sns.scatterplot(..., hue="neighborhood")
show a trend over time line chart sns.lineplot(data=df, x="date", y="visits")
show a noisy daily series raw line + rolling mean s.rolling(7).mean().plot(ax=ax)
show the trend of many groups small multiples sns.relplot(..., kind="line", col="category", col_wrap=3)
show seasonality one line per year, or a month × weekday heatmap sns.lineplot(..., hue="year")
show shares of one whole sorted bars of percentages s.div(s.sum()).sort_values().plot.barh()
show shares across groups 100% stacked bars pd.crosstab(a, b, normalize="index").plot.barh(stacked=True)
show a table of two categories annotated heatmap sns.heatmap(pivot, annot=True, fmt=".0f")
show correlations of many columns heatmap with a diverging map sns.heatmap(corr, vmin=-1, vmax=1, cmap="vlag")
show all pairs of a few columns pair plot sns.pairplot(df[cols].sample(400, random_state=42))
show a model’s errors residuals vs fitted values ax.scatter(pred, y - pred)
show a classifier’s errors confusion matrix ConfusionMatrixDisplay.from_predictions(y, pred)
show an interactive chart with tooltips Plotly Express px.scatter(df, x=..., y=..., hover_name="id")
show a chart for a report Matplotlib or Seaborn, saved as PNG/SVG fig.savefig("output/x.png", dpi=200, bbox_inches="tight")
Question Chart Matplotlib Seaborn Plotly Express Pitfall
how is one variable spread? histogram, ECDF ax.hist(x, bins=30), ax.ecdf(x) histplot, ecdfplot px.histogram, px.ecdf the bin width changes the story; try 2–3
do the groups differ? box, violin, ECDF per group ax.boxplot(groups) boxplot, violinplot, ecdfplot(hue=) px.box, px.violin a box hides two peaks; a violin of 8 points invents a shape
which category is largest? sorted bar ax.barh barplot(estimator="sum") px.bar unsorted bars; an axis that does not start at 0
which group has the highest rate? point or bar + CI ax.errorbar pointplot, barplot(errorbar=) px.bar(error_x=) a bar of a mean with no n or interval
how are two numbers related? scatter ax.scatter(x, y, alpha=0.3) scatterplot, regplot px.scatter(trendline="ols") overplotting; a trend line read as causation
how does it change over time? line ax.plot(dates, y) lineplot px.line bars for hundreds of dates; uneven time gaps drawn as even
how do many series change? small multiples plt.subplots(r, c, sharey=True) relplot(col=) px.line(facet_col=) spaghetti: more than about 5 colored lines on one Axes
what share does each part have? sorted bars, 100% stacked bars ax.barh(..., left=) histplot(multiple="fill") px.bar(barnorm="percent"), px.histogram(barnorm="percent") a pie with many slices; 3-D pies
how do two categories combine? heatmap ax.imshow(m) heatmap(annot=True) px.imshow(text_auto=True) a rainbow colormap
which variables move together? correlation heatmap ax.imshow(corr, vmin=-1, vmax=1) heatmap(corr, mask=) px.imshow(corr, zmin=-1, zmax=1) a sequential map for signed values
where does a model fail? residual plot, confusion matrix ax.scatter(pred, resid) residplot px.scatter residuals against the true values always slope
Library Choose it when Strength Weakness
Matplotlib full control, publication figures, custom layouts every detail is adjustable verbose; you aggregate and label by hand
Seaborn statistical charts from a long DataFrame hue, col, CIs and facets in one call fewer chart types; facets ignore ax=
Plotly Express exploring in a notebook, dashboards, sharing HTML tooltips, zoom, one-call facets large HTML files; static export needs kaleido
pandas .plot a quick look at a Series or a wide frame one line from the data basic styling; it is Matplotlib underneath

Seaborn and pandas draw on Matplotlib Axes, so you can mix them: draw with Seaborn, then fix labels with ax.set(...).

Rule Why How
bars start at 0 bar length encodes the value ax.set_ylim(0, None); lines and dots may zoom
sort categories by value the eye finds the ranking at once order= in Seaborn, sort_values() first
at most about 5 colors more cannot be told apart gray for the rest, highlight one series
same scale across panels panels are compared by eye sharey=True; say so when you free the axis
show the uncertainty of rates small groups look extreme errorbar=("ci", 95) and the n per group
show the data, not only the mean a mean hides skew and outliers strip plot over a box, or an ECDF
log axis for skewed or multiplicative data the bulk of the data is not squeezed into one corner log_scale=True, ax.set_xscale("log")
one message per chart the reader knows what to look at a title that states the finding
label directly a legend forces the eye to jump ax.text at the line ends
color-blind safe palettes about 1 in 12 men has a color-vision deficiency palette="colorblind", viridis, cividis
Data Palette kind Examples
unordered categories qualitative palette="colorblind" (Seaborn), plt.style.use("petroff10") or "tableau-colorblind10" (Matplotlib styles), px.colors.qualitative.Safe; tab10 is not color-blind safe
magnitudes, counts, rates sequential viridis, cividis, rocket, mako
signed values around a midpoint diverging, symmetric limits vlag, RdBu with vmin=-v, vmax=v
anything avoid rainbow maps jet, rainbow add false edges
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
sns.set_theme(style="whitegrid", palette="colorblind")
customers = pd.read_csv("data/customers.csv")
ab = pd.read_csv("data/ab_test.csv")
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])

A rate per group → sorted bars or points with a confidence interval. Aggregate first, so you know the rates and the group sizes:

rates = customers.groupby("contract")["churned"].agg(rate="mean", n="size")
print(rates.sort_values("rate", ascending=False))
Output
rate n
contract
month-to-month 0.296 2784
one-year 0.088 1225
two-year 0.032 991

Chart: sns.barplot(data=customers, x="churned", y="contract", order=rates.sort_values("rate", ascending=False).index, errorbar=("ci", 95), seed=42). The bar is the rate, the line its interval. Write the n per group in the labels when the groups differ in size.

“Did the treatment change time on page?”

Section titled ““Did the treatment change time on page?””

Two distributions → an ECDF per group. Each curve shows the share of users at or below each time. A curve to the right means longer visits, at every percentile:

fig, ax = plt.subplots(figsize=(6, 3.2))
sns.ecdfplot(data=ab, x="time_on_page_s", hue="group", ax=ax)
ax.set(xlabel="time on page (s)", ylabel="share of users", xlim=(0, 400),
title="Treatment users stay longer at every percentile")
print(ab.groupby("group")["time_on_page_s"].median().round(1).to_dict())
plt.show()
Output
{'control': 72.8, 'treatment': 80.8}
Two ECDF curves of time on page: the treatment curve lies a little to the right of the control curve over the whole range, so treatment users stay longer at every percentile.
ECDF per group: compare whole distributions, not only the means.

“How did each category’s revenue move?”

Section titled ““How did each category’s revenue move?””

Six series over 24 months → small multiples with a shared y-axis, not six lines on one Axes:

month = sales["order_date"].dt.to_period("M").dt.to_timestamp()
monthly = (
sales.assign(month=month)
.groupby(["category", "month"], as_index=False)["revenue"].sum()
)
print(monthly.shape, sorted(monthly["category"].unique()))
g = sns.relplot(data=monthly, x="month", y="revenue", col="category", col_wrap=3,
kind="line", height=2.2, aspect=1.5) # one panel per category
g.set_titles("{col_name}")
g.set_axis_labels("", "revenue (k USD)")
for ax in g.axes.flat:
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=[1, 7])) # Jan and Jul
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %y"))
ax.yaxis.set_major_formatter(lambda v, pos: f"{v / 1000:,.0f}")
plt.show()
Output
(144, 3) ['Beauty', 'Books', 'Clothing', 'Electronics', 'Home', 'Sports']
Six small line charts of monthly revenue on a shared y-axis: Electronics earns far more than the rest and jumps in November and December of both years; the other five categories stay low and nearly flat.
Small multiples: one panel per series, one shared scale.

The shared scale shows the true sizes: Electronics dominates. To compare the shapes of the small series, pass facet_kws={"sharey": False} and say so in the title.

“What share of each region’s lines are online?”

Section titled ““What share of each region’s lines are online?””

Parts of a whole across groups → 100% stacked bars. The table behind the chart:

share = pd.crosstab(sales["region"], sales["channel"], normalize="index")
print(share.round(3))
Output
channel online store
region
East 0.422 0.578
North 0.432 0.568
South 0.413 0.587
West 0.413 0.587

Chart: share.plot.barh(stacked=True). Put the share you discuss (online) next to the axis, where all its bars start at 0.

Section titled ““Is price related to size for 3,000 houses?””

Two numbers → a scatter plot. With 3,000 points, use alpha=0.3 or ax.hexbin. Prices are skewed, so log axes show the bulk: sns.scatterplot(data=houses, x="sqft", y="price", alpha=0.3) then ax.set(xscale="log", yscale="log"). Add a trend with sns.regplot(..., scatter=False), and color by neighborhood only if there are at most about 5.

Trap Symptom Fix
a bar axis that starts above 0 a 2% difference looks like 2× start bars at 0, or use dots
a pie with many slices nobody can rank the slices sorted bars of percentages
two y-axes (twinx) the crossing point depends on the scales you chose two panels with a shared x-axis, or index both to 100
unsorted categories the ranking is hard to see order= or sort_values()
alphabetical months or weekdays Apr, Aug, Dec… order=[...] or a categorical dtype
a mean bar per group no hint of n, spread or outliers add a CI, the n, or the points
a KDE near a hard limit density below 0 or above 100% cut=0, or a histogram
overplotting a solid blob of points alpha, smaller markers, hexbin, a sample
a line through unordered x a scribble sort by x, or use a scatter
a numeric hue such as a year a light-to-dark scale, not distinct colors convert it to str
a rainbow colormap false edges, not color-blind safe viridis, cividis, vlag
a sequential map for correlations −0.8 and 0 look alike a diverging map with vmin=-1, vmax=1
free y-axes on small multiples small panels look as big as large ones sharey=True, or say “independent axes”
a raw count compared across groups of different size the bigger group always wins rates, or stat="density", common_norm=False
a Plotly chart of a million rows a huge, slow HTML file aggregate or sample first
plt.savefig after plt.show() an empty image save before you show

A test answers one question: could chance alone explain the difference you see? Four facts pick the test: the outcome type, the number of groups, whether the measurements are paired (the same units measured twice) and whether the assumptions hold. This guide maps those facts to a SciPy or statsmodels function and to the effect size to report next to the p-value. The examples use the checkout A/B test in data/ab_test.csv.

flowchart TD
    A{"Outcome type?"} -->|numeric| B{"How many groups?"}
    A -->|"binary (a rate)"| P{"How many groups?"}
    A -->|"two categoricals"| X["chi2_contingency<br/>fisher_exact if small"]
    A -->|"two numerics"| C["pearsonr / spearmanr"]
    B -->|1| B1["ttest_1samp<br/>or wilcoxon"]
    B -->|2| B2{"Paired?"}
    B2 -->|yes| B3["ttest_rel<br/>or wilcoxon"]
    B2 -->|no| B4["Welch ttest_ind<br/>or mannwhitneyu"]
    B -->|"3+"| B5{"Paired?"}
    B5 -->|yes| B6["AnovaRM<br/>or friedmanchisquare"]
    B5 -->|no| B7["Welch f_oneway, then Games–Howell;<br/>or kruskal, then pairwise<br/>mannwhitneyu + Holm"]
    P -->|1| P1["binomtest"]
    P -->|2| P2{"Paired?"}
    P2 -->|yes| P3["mcnemar"]
    P2 -->|no| P4["proportions_ztest<br/>fisher_exact if small"]
    P -->|"3+"| P5["chi2_contingency"]

In each box, the first test assumes a roughly normal mean (or large samples); the second one (after “or”) uses ranks and suits skewed, ordinal or small data.

I want to… Use… Effect size to report
compare a mean with a target stats.ttest_1samp(x, popmean=m) mean − target, with its CI
compare two independent means stats.ttest_ind(a, b, equal_var=False) (Welch) difference with CI, Cohen’s d
compare two skewed or ordinal groups stats.mannwhitneyu(a, b) rank-biserial r, difference of medians with a bootstrap CI
compare before/after on the same units stats.ttest_rel(after, before) mean difference, dzd_z
compare skewed paired data stats.wilcoxon(after, before) median difference
compare 3+ independent means stats.f_oneway(*groups, equal_var=False) η²
compare 3+ skewed groups stats.kruskal(*groups) ε²
find which pairs differ (means) stats.tukey_hsd(*groups, equal_var=False) (Games–Howell) pairwise differences with CIs
find which pairs differ (ranks) mannwhitneyu per pair + multipletests(p, method="holm") rank-biserial r per pair
compare 3+ conditions on the same units AnovaRM(df, "y", "subject", within=["cond"]).fit() partial η²
the same, with skewed data stats.friedmanchisquare(a, b, c) Kendall’s W
test one rate against a value stats.binomtest(k, n, p=p0) rate − p0, .proportion_ci()
compare two rates proportions_ztest([k1, k2], [n1, n2]) difference in percentage points, relative lift
a CI for a difference of rates confint_proportions_2indep(k1, n1, k2, n2, method="newcomb")
compare two rates with small counts stats.fisher_exact(table) odds ratio
compare paired yes/no outcomes mcnemar(table, exact=True) discordant pairs
test two categorical variables stats.chi2_contingency(pd.crosstab(a, b)) Cramér’s V
test counts against expected shares stats.chisquare(obs, f_exp=expected_counts)
a linear relation of two numbers stats.pearsonr(x, y) r with .confidence_interval()
a monotonic relation, outliers, ranks stats.spearmanr(x, y), stats.kendalltau(x, y) ρ, τ
any difference between two distributions stats.ks_2samp(a, b) the KS statistic
a p-value for any statistic stats.permutation_test((a, b), stat, rng=rng) the statistic itself
a CI for any statistic stats.bootstrap((x,), np.median, rng=rng)
control for other variables smf.ols("y ~ group + x", df), smf.logit(...) the coefficient with its CI
check normality stats.probplot(x) (Q-Q plot)
check equal variances stats.levene(a, b)
adjust many p-values stats.false_discovery_control(p), multipletests(p, method="holm")
plan the sample size NormalIndPower().solve_power(effect_size=h, power=0.8)

Imports: from scipy import stats; from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep; from statsmodels.stats.contingency_tables import mcnemar; from statsmodels.stats.anova import AnovaRM; from statsmodels.stats.power import NormalIndPower; from statsmodels.stats.proportion import proportion_effectsize; from statsmodels.stats.multitest import multipletests; import statsmodels.formula.api as smf.

Outcome Groups Paired Data Test Function Effect size
numeric 1 — mean roughly normal one-sample t ttest_1samp(x, popmean=m) (xˉ−m)/s(\bar x - m)/s
numeric 1 — skewed Wilcoxon signed-rank wilcoxon(x - m) median − m
numeric 2 no means, any variances Welch t ttest_ind(a, b, equal_var=False) aˉ−bˉ\bar a - \bar b with CI; Cohen’s d
numeric 2 no skewed, ordinal, outliers Mann–Whitney U mannwhitneyu(a, b) rank-biserial 2U/(n1n2)−12U/(n_1 n_2) - 1
numeric 2 no unequal spreads, ranks Brunner–Munzel brunnermunzel(a, b) P(A>B)P(A > B)
numeric 2 yes differences roughly normal paired t ttest_rel(after, before) dz=dˉ/sdd_z = \bar d / s_d
numeric 2 yes skewed differences Wilcoxon signed-rank wilcoxon(after, before) median difference
numeric 3+ no means one-way ANOVA (Welch) f_oneway(*g, equal_var=False) η² = SS_between / SS_total
numeric 3+ no skewed Kruskal–Wallis kruskal(*g) ε² = H / (n − 1)
numeric 3+ no all pairs of means, unequal variances Games–Howell tukey_hsd(*g, equal_var=False) pairwise differences with CIs
numeric 3+ no all pairs of means, similar SDs Tukey HSD tukey_hsd(*g) pairwise differences with CIs
numeric 3+ no all pairs after Kruskal–Wallis pairwise Mann–Whitney + Holm mannwhitneyu per pair, multipletests(p, method="holm") rank-biserial r per pair
numeric 3+ yes balanced, normal-ish repeated-measures ANOVA AnovaRM(...).fit() partial η²
numeric 3+ yes skewed Friedman friedmanchisquare(a, b, c) Kendall’s W
binary 1 — k successes of n exact binomial binomtest(k, n, p=p0) p^−p0\hat p - p_0 with CI
binary 2 no every cell ≥ 5 expected two-proportion z proportions_ztest([k1, k2], [n1, n2]) p^1−p^2\hat p_1 - \hat p_2, relative lift, Cohen’s h
binary 2 no small counts Fisher exact fisher_exact(table) odds ratio
binary 2 yes the same units twice McNemar mcnemar(table, exact=True) difference of discordant shares
binary or categorical 2+ no every cell ≥ 5 expected chi-square independence chi2_contingency(table) Cramér’s V
counts 1 — observed vs expected shares chi-square goodness of fit chisquare(obs, f_exp=exp) —
two numerics — — linear, no big outliers Pearson pearsonr(x, y) r
two numerics — — monotonic, ordinal, outliers Spearman, Kendall spearmanr(x, y), kendalltau(x, y) ρ, τ
numeric 2 no any shape difference Kolmogorov–Smirnov ks_2samp(a, b) D
anything 2+ either no formula fits permutation test permutation_test(data, stat) your statistic
anything — — other variables matter regression smf.ols, smf.logit coefficient with CI

The two-proportion z-test and chi2_contingency(table, correction=False) on the same 2×2 table give the same p-value: χ2=z2\chi^2 = z^2.

Assumption Used by Check If it fails
independent observations every test above the design: one row per unit, random assignment aggregate to one value per unit, or use a mixed model; test by cluster
the mean is roughly normal t-tests, ANOVA Q-Q plot of each group (stats.probplot); n ≥ 30 per group usually suffices unless the data are very skewed rank test, bootstrap, permutation test, or a log transform
equal variances Student t, classic ANOVA, Tukey HSD stats.levene(a, b), compare the SDs Welch versions: equal_var=False (use them by default)
similar shapes Mann–Whitney, Kruskal as tests of medians histograms or ECDFs read them as “one group tends to be larger”, or use Brunner–Munzel
expected counts ≥ 5 chi-square, z-test for rates chi2_contingency(t).expected_freq fisher_exact, barnard_exact, merge sparse categories
continuous data KS test many ties mean it is not a chi-square test on bins
a linear relation Pearson, OLS scatter plot, residual plot Spearman, a transform, a flexible model

Do not use a significant Shapiro–Wilk test as a gate. With thousands of rows, it rejects harmless departures. With 10 rows, it misses large ones. Read the Q-Q plot.

A p-value says whether an effect is distinguishable from noise. An effect size says how large it is. Report both, with a confidence interval.

Effect size Formula or code Rough scale
difference of means ttest_ind(...).confidence_interval() in the data’s units: the most useful
Cohen’s d (xˉ1−xˉ2)/sp(\bar x_1 - \bar x_2)/s_p 0.2 small, 0.5 medium, 0.8 large
difference of rates p^1−p^2\hat p_1 - \hat p_2, confint_proportions_2indep percentage points
relative lift (p^1−p^2)/p^2(\hat p_1 - \hat p_2)/\hat p_2 business context
relative risk stats.contingency.relative_risk(k1, n1, k2, n2) 1 = no effect
odds ratio stats.contingency.odds_ratio(table) 1 = no effect
Cohen’s h proportion_effectsize(p1, p2) input for power analysis
rank-biserial r 2U/(n1n2)−12U/(n_1 n_2) - 1 −1 to 1; 0 = no tendency
r, ρ pearsonr, spearmanr 0.1 small, 0.3 medium, 0.5 large
Cramér’s V stats.contingency.association(table) 0.1 weak, 0.3 moderate (2 columns)
η², ε² between-group SS / total SS; H / (n − 1) share of variance explained
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.stats.proportion import confint_proportions_2indep, proportions_ztest
ab = pd.read_csv("data/ab_test.csv")
t = ab[ab["group"] == "treatment"]
c = ab[ab["group"] == "control"]
rng = np.random.default_rng(42)

Binary outcome, two independent groups, thousands of users per group → two-proportion z-test. Report the difference with its CI:

k = [int(t["converted"].sum()), int(c["converted"].sum())]
n = [len(t), len(c)]
z, p = proportions_ztest(k, n)
low, high = confint_proportions_2indep(k[0], n[0], k[1], n[1], method="newcomb")
print(f"treatment {k[0] / n[0]:.2%}, control {k[1] / n[1]:.2%}, p = {p:.4f}")
print(f"difference: 95% CI [{low:.2%}, {high:.2%}]")
Output
treatment 11.66%, control 10.12%, p = 0.0129
difference: 95% CI [0.33%, 2.77%]

Numeric outcome, two independent groups, large n, some skew → Welch t-test, with Mann–Whitney as a robustness check. Cohen’s d sizes the effect:

a, b = t["time_on_page_s"].to_numpy(), c["time_on_page_s"].to_numpy()
res = stats.ttest_ind(a, b, equal_var=False)
pooled = np.sqrt((a.var(ddof=1) + b.var(ddof=1)) / 2) # equal-n approximation
print(f"skew {stats.skew(a):.2f}, Welch p = {res.pvalue:.1e}")
print(f"difference CI {np.round(res.confidence_interval(), 1)} s")
print(f"d = {(a.mean() - b.mean()) / pooled:.2f}, Mann-Whitney p = "
f"{stats.mannwhitneyu(a, b).pvalue:.1e}")
Output
skew 1.27, Welch p = 2.5e-17
difference CI [ 6.9 11.1] s
d = 0.17, Mann-Whitney p = 4.1e-20

A tiny p-value with d = 0.17 means a small effect that is clearly real. Whether 9 more seconds matter is a business question, not a statistical one.

Revenue of buyers is skewed (a few large orders) → Mann–Whitney for the test, a bootstrap CI for the difference of medians:

tr = t.loc[t["converted"] == 1, "revenue"].to_numpy()
cr = c.loc[c["converted"] == 1, "revenue"].to_numpy()
def median_diff(x, y, axis):
return np.median(x, axis=axis) - np.median(y, axis=axis)
ci = stats.bootstrap((tr, cr), median_diff, n_resamples=2000, rng=rng)
mw = stats.mannwhitneyu(tr, cr)
print(f"skew {stats.skew(tr):.1f}, Mann-Whitney p = {mw.pvalue:.3f}")
print(f"median difference CI [{ci.confidence_interval.low:.2f}, "
f"{ci.confidence_interval.high:.2f}]")
Output
skew 2.4, Mann-Whitney p = 0.282
median difference CI [-5.40, 2.06]

The CI includes 0: no evidence that the value of an order changed. This compares buyers only, and the treatment changes who buys (more conversions). For the effect of the treatment on money, compare revenue per user over all users, zeros included:

rev_t, rev_c = t["revenue"].to_numpy(), c["revenue"].to_numpy()
res_rev = stats.ttest_ind(rev_t, rev_c, equal_var=False) # n is large: CLT
print(f"revenue per user {rev_t.mean():.2f} vs {rev_c.mean():.2f}, "
f"p = {res_rev.pvalue:.3f}, CI {np.round(res_rev.confidence_interval(), 2)}")
Output
revenue per user 4.85 vs 4.38, p = 0.157, CI [-0.18 1.11]

Revenue per user is 0.47 higher in the treatment group, but the CI includes 0: the test cannot yet show a revenue effect.

“Which devices differ in time on page?”

Section titled ““Which devices differ in time on page?””

Three groups → an omnibus test, then a pairwise follow-up that matches it. After Welch ANOVA, use Games–Howell (tukey_hsd with equal_var=False). After Kruskal–Wallis, use pairwise Mann–Whitney tests with a Holm correction. Tukey HSD controls the family-wise error rate itself, so it does not need a significant omnibus test first:

from itertools import combinations
from statsmodels.stats.multitest import multipletests
devices = sorted(ab["device"].unique())
groups = [ab.loc[ab["device"] == d, "time_on_page_s"].to_numpy() for d in devices]
print(devices, "SDs", [round(float(g.std(ddof=1)), 1) for g in groups])
print(f"Welch ANOVA p = {stats.f_oneway(*groups, equal_var=False).pvalue:.1e}")
gh = stats.tukey_hsd(*groups, equal_var=False) # Games-Howell
pairs = list(combinations(range(len(devices)), 2))
raw = [stats.mannwhitneyu(groups[i], groups[j]).pvalue for i, j in pairs]
holm = multipletests(raw, method="holm")[1]
for (i, j), p_holm in zip(pairs, holm, strict=True):
print(f"{devices[i]:>7} vs {devices[j]:<7} Games-Howell p = {gh.pvalue[i, j]:.3f}"
f" Mann-Whitney + Holm p = {p_holm:.3f}")
Output
['desktop', 'mobile', 'tablet'] SDs [53.9, 51.9, 55.3]
Welch ANOVA p = 3.5e-40
desktop vs mobile Games-Howell p = 0.000 Mann-Whitney + Holm p = 0.000
desktop vs tablet Games-Howell p = 0.000 Mann-Whitney + Holm p = 0.000
mobile vs tablet Games-Howell p = 0.642 Mann-Whitney + Holm p = 0.884

Both follow-ups agree: desktop differs from mobile and tablet; mobile and tablet do not differ. Here the SDs are similar, so plain tukey_hsd(*groups) would give almost the same answer.

“Does conversion depend on the device?”

Section titled ““Does conversion depend on the device?””

Two categorical variables (3 devices × converted) → chi-square test of independence and Cramér’s V:

table = pd.crosstab(ab["device"], ab["converted"])
chi = stats.chi2_contingency(table)
print(table)
print(f"p = {chi.pvalue:.1e}, min expected = {chi.expected_freq.min():.0f}, "
f"V = {stats.contingency.association(table):.3f}")
Output
converted 0 1
device
desktop 2974 454
mobile 5061 516
tablet 876 119
p = 1.4e-08, min expected = 108, V = 0.060

The minimum expected count is far above 5, so the test is valid. V ≈ 0.06 is a weak association: the dependence is real but small.

Paired numeric data → test the differences. An unpaired test on the same numbers loses the pairing and most of its power:

before = np.array([31.0, 28.5, 40.2, 35.1, 22.8, 30.4, 27.9, 33.6])
after = np.array([29.2, 27.9, 37.5, 34.0, 22.1, 28.3, 27.5, 31.4])
print(f"paired t p = {stats.ttest_rel(after, before).pvalue:.4f}")
print(f"Wilcoxon p = {stats.wilcoxon(after, before).pvalue:.4f}")
print(f"unpaired p = {stats.ttest_ind(after, before).pvalue:.4f} (wrong test)")
Output
paired t p = 0.0020
Wilcoxon p = 0.0078
unpaired p = 0.5665 (wrong test)

“Did the treatment work in each country?”

Section titled ““Did the treatment work in each country?””

Seven tests at α = 0.05 → expect false positives. Adjust the p-values with Benjamini–Hochberg (false discovery rate):

pvals = {}
for country, g in ab.groupby("country"):
table = pd.crosstab(g["group"], g["converted"])
pvals[country] = stats.chi2_contingency(table, correction=False).pvalue
raw = pd.Series(pvals)
result = pd.DataFrame({"p": raw, "p_bh": stats.false_discovery_control(raw)})
print(result.round(3).sort_values("p"))
Output
p p_bh
CA 0.025 0.176
FR 0.068 0.237
DE 0.120 0.280
US 0.209 0.340
AU 0.243 0.340
UK 0.516 0.603
IN 0.707 0.707

Canada looks significant alone (p ≈ 0.025) but not after the adjustment. Decide on subgroup tests before you see the data, and report them as exploratory.

Trap Symptom Fix
Student t (ttest_ind default) with unequal variances wrong p-values equal_var=False (Welch) always
tukey_hsd(*g) after Kruskal–Wallis or Welch ANOVA a follow-up that assumes equal variances and normal means Games–Howell (equal_var=False), or pairwise mannwhitneyu + Holm
an unpaired test on paired data a large p-value; the effect is missed ttest_rel or wilcoxon on the pairs
many rows per user treated as independent p-values far too small one value per user, or a mixed model
a normality test as a gate big n: always “not normal”; small n: never read a Q-Q plot; think about the CLT
Mann–Whitney read as a test of medians wrong claims when shapes differ “group A tends to be larger”; bootstrap the median difference
chi-square with expected counts below 5 an unreliable p-value fisher_exact, barnard_exact, or merge categories
chi2_contingency on a 2×2 table vs a z-test the p-values differ Yates’ correction; correction=False matches the z-test
chisquare with shares as f_exp ValueError: the sums differ expected counts: shares * obs.sum()
a significant p-value read as a big effect a 0.1-point change “proven” with a million rows report the effect size and its CI
“p > 0.05, so no effect” an underpowered test read as proof report the CI; plan power in advance
testing many metrics or segments false discoveries pick one primary metric; adjust with BH or Holm
peeking at a running A/B test the false-positive rate grows far above α fix n in advance, or use a sequential design
a one-sided test chosen after seeing the data a p-value half as large, but invalid decide the direction before collecting data
“observed power” after a test it is only a restatement of the p-value do power analysis before the test
a correlation read as causation confounders explain the link an experiment, or adjust in a regression
alternative="greater" the direction looks reversed it means first argument > second argument
NaN in the input the result is nan nan_policy="omit" or dropna()

No algorithm wins everywhere. The data type, the number of rows, the need to explain each prediction and the time budget narrow the choice to two or three candidates. Then cross-validation decides. This guide profiles the supervised, unsupervised, time-series, text and deep learning models of the course.

flowchart TD
    A{"Labeled target?"} -->|no| U{"Goal?"}
    U -->|groups| U1["KMeans / GMM / HDBSCAN"]
    U -->|"fewer dimensions"| U2["PCA;<br/>t-SNE / UMAP to plot"]
    U -->|"unusual rows"| U3["IsolationForest / LOF"]
    A -->|yes| B{"Data type?"}
    B -->|"images, audio"| NN["CNN in PyTorch,<br/>or a pretrained model"]
    B -->|text| TX["TF-IDF + linear model;<br/>embeddings"]
    B -->|"time series"| TS["seasonal naive, then<br/>SARIMA or boosting on lags"]
    B -->|tabular| C{"Must explain each<br/>weight or rule?"}
    C -->|yes| L["regularized linear model,<br/>shallow tree"]
    C -->|no| D{"How many rows?"}
    D -->|"under ~10,000"| D1["linear, SVM, random forest,<br/>HistGradientBoosting"]
    D -->|"10,000 or more"| D2["HistGradientBoosting,<br/>LightGBM, XGBoost"]

Always fit a baseline first (DummyRegressor, DummyClassifier, a seasonal naive forecast). A model is only useful if it beats the baseline by a margin that matters.

I want to… Use… Notes
a baseline for regression DummyRegressor(strategy="median") the score any model must beat
a baseline for classification DummyClassifier(strategy="prior") AP equals the positive share
a fast, explainable regression RidgeCV(alphas=np.logspace(-3, 3, 13)) scale first
select features automatically LassoCV() or ElasticNetCV() zeros some coefficients
an explainable classifier with odds ratios LogisticRegression(C=1.0) scale first; np.exp(coef_)
the best accuracy on a table HistGradientBoostingClassifier / Regressor native NaN and categories
very large tables (millions of rows) lightgbm.LGBMClassifier(verbose=-1) num_leaves, early stopping
a GPU-capable boosting model xgboost.XGBClassifier(device="cuda") enable_categorical=True
a strong default with little tuning RandomForestClassifier(n_estimators=300) oob_score=True for a free check
readable if-then rules DecisionTreeClassifier(max_depth=3) export_text(tree)
a model for a few hundred clean rows SVC(C=..., gamma=...) in a pipeline with a scaler CalibratedClassifierCV for probabilities
predictions from similar cases KNeighborsClassifier(n_neighbors=15) scale first; slow on large data
a model in milliseconds GaussianNB(), MultinomialNB() (text) poor probabilities
combine different good models VotingClassifier(voting="soft"), StackingClassifier gains are usually small
groups of similar rows KMeans(n_clusters=k, n_init=10) scale first; choose k with silhouette
clusters of any shape plus noise HDBSCAN(min_cluster_size=...) label −1 = noise
soft cluster memberships GaussianMixture(n_components=k) choose k with BIC
compress correlated features PCA(n_components=0.9) keeps 90% of the variance
a 2-D picture of high-dimensional data TSNE(perplexity=30), umap.UMAP(n_jobs=1) for viewing only
flag anomalies IsolationForest(contamination=0.01) no scaling needed
forecast a series seasonal naive → SARIMAX → boosting on lag features backtest with TimeSeriesSplit
classify text TfidfVectorizer + LogisticRegression(C=10) LinearSVC is often a bit more accurate
find topics in text NMF on TF-IDF, LatentDirichletAllocation on counts read the top words
images, audio, raw signals a CNN in PyTorch, or fine-tune a pretrained model needs much data or transfer learning
explain any model permutation_importance, SHAP, partial dependence on held-out data

“Scale?” means the model needs standardized inputs (StandardScaler in a pipeline). “NaN” means fit accepts missing values without an imputer. “Interpretability”: high = read the weights or rules directly; low = needs SHAP or permutation importance.

Model Class Strengths Weaknesses Scale? Missing / categorical Key hyperparameters Typical size Interpretability
Linear regression, Ridge, Lasso, ElasticNet LinearRegression, RidgeCV, LassoCV, ElasticNetCV fast, stable, extrapolates a trend, small data linear only unless you add features; OLS is pulled by outliers yes for penalized models impute; one-hot (drop one level for plain OLS) alpha, l1_ratio any; good when rows are few or features many high: coefficients
Logistic regression LogisticRegression well-calibrated probabilities, odds ratios, fast linear log-odds yes impute; one-hot C (smaller = stronger penalty), l1_ratio, class_weight any high: odds ratios
k-nearest neighbors KNeighborsClassifier, KNeighborsRegressor no training, local patterns slow predictions, weak in many dimensions, stores all data yes, essential impute (KNNImputer); one-hot n_neighbors, weights, metric up to ~100k rows, few features medium: “similar cases”
Naive Bayes GaussianNB, MultinomialNB, ComplementNB milliseconds, tiny data, text assumes independent features; overconfident probabilities no impute; counts for MultinomialNB var_smoothing, alpha tiny to huge medium: per-feature likelihoods
Support vector machine SVC, SVR, LinearSVC strong on small, clean data; kernels for curves kernel SVMs are slow above ~20k rows; no native probabilities yes, essential impute; one-hot C, kernel, gamma kernel: under ~20k rows; LinearSVC: large sparse data low (kernel), medium (linear)
Decision tree DecisionTreeClassifier, DecisionTreeRegressor readable rules, curves and interactions unstable, overfits, step-shaped predictions no NaN: yes; ordinal or one-hot encoding max_depth, min_samples_leaf, ccp_alpha any high when shallow
Random forest, extra trees RandomForestClassifier, ExtraTreesRegressor, … strong default, little tuning, free OOB score large models, slower predictions, no extrapolation no NaN: yes; ordinal encoding is fine n_estimators, max_features, min_samples_leaf 1k to ~1M rows low: permutation importance, SHAP
Histogram gradient boosting HistGradientBoostingClassifier, …Regressor top accuracy on tables, fast needs tuning for the last few points no NaN: yes; categories: native (category dtype) learning_rate, max_iter, max_leaf_nodes, l2_regularization, early_stopping best from ~10k rows; fine below low: SHAP, partial dependence
XGBoost xgboost.XGBClassifier, XGBRegressor top accuracy, GPU, many options many parameters no NaN: yes; enable_categorical=True n_estimators, learning_rate, max_depth, subsample, colsample_bytree, early_stopping_rounds 10k to 100M rows low: SHAP
LightGBM lightgbm.LGBMClassifier, LGBMRegressor fastest on large data leaf-wise trees overfit small data no NaN: yes; pandas category columns natively num_leaves, learning_rate, n_estimators, min_child_samples 100k+ rows low: SHAP
Neural network MLPClassifier, PyTorch nn.Module images, text, audio; any function needs much data, compute and tuning; rarely beats boosting on tables yes impute; one-hot or embeddings layers, width, learning rate, weight_decay, dropout, epochs, batch size 10k+ rows; far more for images low
Voting, stacking VotingClassifier, StackingRegressor small extra accuracy from different models slower; harder to maintain and explain as its members as its members estimators, voting, final_estimator, cv any low
import lightgbm as lgb
import numpy as np
import xgboost as xgb
from sklearn.datasets import make_classification
from sklearn.ensemble import (
GradientBoostingClassifier,
HistGradientBoostingClassifier,
RandomForestClassifier,
)
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
X_nan, y_nan = make_classification(n_samples=200, n_features=4, random_state=42)
X_nan[::10, 0] = np.nan # 10% missing in one column
models = [
LogisticRegression(), KNeighborsClassifier(), SVC(),
GradientBoostingClassifier(n_estimators=10),
DecisionTreeClassifier(random_state=42),
RandomForestClassifier(n_estimators=10, random_state=42),
HistGradientBoostingClassifier(max_iter=10),
xgb.XGBClassifier(n_estimators=10), lgb.LGBMClassifier(n_estimators=10, verbose=-1),
]
for model in models:
try:
model.fit(X_nan, y_nan)
result = "accepts NaN"
except ValueError:
result = "ValueError: impute first"
print(f"{type(model).__name__:<31} {result}")
Output
LogisticRegression ValueError: impute first
KNeighborsClassifier ValueError: impute first
SVC ValueError: impute first
GradientBoostingClassifier ValueError: impute first
DecisionTreeClassifier accepts NaN
RandomForestClassifier accepts NaN
HistGradientBoostingClassifier accepts NaN
XGBClassifier accepts NaN
LGBMClassifier accepts NaN

The models that accept NaN learn which branch the missing values follow. That treats “missing” as information, which helps when missingness itself predicts the target. Put a SimpleImputer in the pipeline for the others; add add_indicator=True to keep the “was missing” signal.

Distance-based and penalized models compare features on one scale. Trees split one feature at a time and do not care. The wine data has features from 0.1 to 1,680:

from sklearn.datasets import load_wine
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X_wine, y_wine = load_wine(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
candidates = {
"KNN": KNeighborsClassifier(),
"SVC (RBF)": SVC(),
"logistic": LogisticRegression(max_iter=10_000),
"forest": RandomForestClassifier(random_state=42),
}
for name, model in candidates.items():
raw = cross_val_score(model, X_wine, y_wine, cv=cv).mean()
scaled = cross_val_score(
make_pipeline(StandardScaler(), model), X_wine, y_wine, cv=cv
).mean()
print(f"{name:<10} raw {raw:.3f} scaled {scaled:.3f}")
Output
KNN raw 0.680 scaled 0.972
SVC (RBF) raw 0.674 scaled 0.983
logistic raw 0.966 scaled 0.983
forest raw 0.977 scaled 0.977
Scaler Use when
StandardScaler the default for linear models, SVM, KNN, PCA, neural networks
RobustScaler outliers would dominate the mean and SD
MinMaxScaler a bounded range is required (some neural network inputs, images)
QuantileTransformer, PowerTransformer very skewed features for linear or distance models
none trees, forests, boosting, naive Bayes
from sklearn.datasets import load_breast_cancer
from sklearn.dummy import DummyClassifier
X_bc, y_bc = load_breast_cancer(return_X_y=True)
shortlist = {
"baseline": DummyClassifier(strategy="prior"),
"logistic": make_pipeline(StandardScaler(), LogisticRegression()),
"forest": RandomForestClassifier(n_estimators=200, random_state=42),
"boosting": HistGradientBoostingClassifier(random_state=42),
}
for name, model in shortlist.items():
scores = cross_val_score(model, X_bc, y_bc, cv=cv, scoring="roc_auc")
print(f"{name:<9} ROC-AUC {scores.mean():.3f} +/- {scores.std():.3f}")
Output
baseline ROC-AUC 0.500 +/- 0.000
logistic ROC-AUC 0.995 +/- 0.005
forest ROC-AUC 0.990 +/- 0.008
boosting ROC-AUC 0.992 +/- 0.006

On 569 rows with a near-linear signal, the scaled logistic regression is as good as the ensembles. It is faster and easier to explain, so it wins. On large tables with interactions, boosting usually leads.

Model Class Strengths Weaknesses Scale? Missing / categorical Key hyperparameters Typical size Interpretability
k-means KMeans, MiniBatchKMeans fast, simple, predict for new rows you choose k; round clusters of similar size; outliers pull centroids yes impute; numeric only n_clusters, n_init=10 up to millions (mini-batch) high: centroids
Hierarchical (Ward) AgglomerativeClustering, scipy...linkage a dendrogram; choose k after fitting memory grows with n²; no predict yes impute; numeric n_clusters or distance_threshold, linkage under ~20k rows high: the tree
DBSCAN, HDBSCAN DBSCAN, HDBSCAN any cluster shape; marks noise (−1); no k eps is hard to choose (DBSCAN); no predict yes impute; numeric eps, min_samples; min_cluster_size under ~100k rows medium
Gaussian mixture GaussianMixture soft probabilities, elliptical clusters, BIC for k assumes Gaussian blobs; local optima yes impute; numeric n_components, covariance_type under ~100k rows medium: means and covariances
PCA PCA, IncrementalPCA fast, decorrelates, compresses, denoises linear; each component mixes features yes impute; numeric n_components (int or variance share) any medium: loadings
t-SNE TSNE clear 2-D maps of local neighbors no transform; gaps and sizes mean nothing; slow yes impute; numeric perplexity under ~50k rows low: for viewing only
UMAP umap.UMAP faster than t-SNE; transform for new rows same reading caveats as t-SNE yes impute; numeric n_neighbors, min_dist up to millions low
Isolation forest IsolationForest many features, no scaling, fast contamination is a quota, not a discovery no NaN: accepted in scikit-learn 1.9; numeric contamination, n_estimators any low: anomaly score
Local outlier factor LocalOutlierFactor local, density-based anomalies slow on large data; novelty=True to score new rows yes impute; numeric n_neighbors, contamination, novelty under ~100k rows low

Categorical columns are a poor fit for distance-based clustering: one-hot columns dominate the distances. Cluster on numeric behavior, then profile the clusters with the categorical columns.

Model How Strengths Weaknesses Scale? Missing values Key hyperparameters Typical size Interpretability
naive, seasonal naive last value, or the value one season ago the baseline; hard to beat at short horizons no trend, no inputs no needs a regular index season length m any high
ETS (exponential smoothing) statsmodels.tsa.holtwinters.ExponentialSmoothing trend and one seasonality, fast no external inputs no fill gaps first trend, seasonal, damped_trend two or more seasons high: smoothing weights
SARIMA / SARIMAX statsmodels...SARIMAX prediction intervals, known future inputs (exog) one seasonality; slow for long seasons (s=365); convergence issues no fill gaps first order=(p, d, q), seasonal_order=(P, D, Q, s) 50 to a few thousand points medium: coefficients
Boosting on lag features LGBMRegressor on shift/rolling features many series, many inputs, nonlinear cannot extrapolate a trend; recursive multi-step forecasts; leakage risk no NaN: yes lags, window sizes, plus boosting parameters 1k+ rows low
Model Input Strengths Weaknesses Key hyperparameters Typical size Interpretability
LogisticRegression TF-IDF probabilities, readable word weights bag of words: word order lost beyond n-grams C (try 10), ngram_range, min_df 1k to millions of documents high: top words
LinearSVC TF-IDF often the most accurate linear model no predict_proba C same high
MultinomialNB, ComplementNB counts very fast, strong on small data overconfident probabilities alpha small to huge medium
SGDClassifier TF-IDF streams and huge corpora (partial_fit) needs tuning alpha, loss millions high
NMF, LatentDirichletAllocation TF-IDF, counts topics without labels you choose the number of topics n_components 1k+ documents medium: top words
embeddings (LSA, pretrained transformers) + a linear model dense vectors meaning, synonyms compute cost; black box model choice, dimensions any low

Trees and KNN are rarely good on sparse text: thousands of sparse columns make splits and distances weak.

Situation Shortlist Why
predict churn for 5,000 customers, managers want reasons logistic regression; then boosting if it gains enough odds ratios explain; boosting sets the accuracy ceiling
house prices, 3,000 rows, skewed target Ridge on log price; HistGradientBoosting log fixes the skew; boosting captures neighborhood × size
fraud in 10M transactions, 0.1% positive LightGBM with early stopping, then a tuned threshold speed at scale; rare class needs AP and a cost threshold
300 lab samples, 20 clean numeric features logistic regression, SVM, random forest with repeated CV small data: simple models, stable estimates
segment customers for marketing scaled k-means, k from silhouette and business sense centroids are easy to name and act on
detect faulty sensor readings, no labels IsolationForest per machine, rolling features no scaling; one model per machine avoids flagging a whole machine
forecast daily web visits 28 days ahead seasonal naive, SARIMA, boosting on lags; backtest all the baseline often wins at short horizons
classify 3,000 product reviews TF-IDF + logistic regression strong, fast, readable
classify photos fine-tune a pretrained CNN transfer learning needs far fewer images
Trap Symptom Fix
KNN, SVM or a penalized model without scaling poor scores; one feature dominates make_pipeline(StandardScaler(), model)
scaling fitted on all rows optimistic CV scores the scaler inside the pipeline
KMeans() with default n_init a worse local minimum n_init=10
a deep tree’s training score R² = 1.0 or 100% accuracy limit max_depth; judge on CV
trees or boosting asked to extrapolate flat predictions beyond the training range linear model, or a target with no trend (differences, ratios)
RandomForestRegressor() defaults plain bagging: max_features=1.0 try max_features 0.3–0.6
HistGradientBoosting early stopping off below 10,000 rows ("auto") early_stopping=True with a validation share
LightGBM on a few hundred rows overfits; terminal logs larger min_child_samples, verbose=-1
SVC on 100k rows training takes hours LinearSVC, SGDClassifier, or boosting
SVC.predict_proba slow, and inconsistent with predict CalibratedClassifierCV, or a model with native probabilities
GaussianNB probabilities often near 0 or 1 use for ranking only, or calibrate
one-hot encoding of a high-cardinality column thousands of columns; slow models TargetEncoder in the pipeline, or native categories in boosting
clusters found on a t-SNE map artifacts of the map cluster on the original (scaled) features
a neural network on a small table worse than boosting, after hours try boosting first
an ensemble of models that agree no gain, more cost check the correlation of their predictions
choosing by the test-set score an optimistic, unrepeatable result choose with CV; look at the test set once

A metric turns “is the model good?” into a number. Choose it from the decision the model supports, before you train anything: what does an error cost, and which errors cost most? This guide maps task and business goal to a metric, gives its formula and scikit-learn name, and shows when it misleads.

flowchart TD
    A{"Task?"} -->|regression| R{"Which errors hurt?"}
    R -->|"all units alike"| R1["MAE"]
    R -->|"big misses most"| R2["RMSE"]
    R -->|"relative, y above 0"| R3["MAPE / RMSLE"]
    A -->|classification| C{"What is the output used for?"}
    C -->|"probabilities"| C1["log loss, Brier,<br/>calibration curve"]
    C -->|"a ranking"| C2{"Rare positives?"}
    C2 -->|yes| C3["average precision,<br/>precision at k"]
    C2 -->|no| C4["ROC-AUC"]
    C -->|"yes/no decisions"| C5{"Error costs known?"}
    C5 -->|yes| C6["expected cost<br/>at a tuned threshold"]
    C5 -->|no| C7["F1, or recall at<br/>a fixed precision"]
    A -->|forecast| F["MASE, MAE"]
    A -->|clustering| K["silhouette without labels,<br/>ARI with labels"]
I want to… Use… scoring= string
the average error in the target’s units mean_absolute_error "neg_mean_absolute_error"
punish big misses more root_mean_squared_error "neg_root_mean_squared_error"
the share of variance explained r2_score "r2"
a percentage error (y never near 0) mean_absolute_percentage_error "neg_mean_absolute_percentage_error"
errors on a log scale (prices, counts) root_mean_squared_log_error "neg_root_mean_squared_log_error"
errors robust to a few outliers median_absolute_error "neg_median_absolute_error"
an error for an under/over-forecast trade-off mean_pinball_loss(y, q_pred, alpha=0.9) make_scorer(..., greater_is_better=False)
the share of correct labels (balanced classes) accuracy_score "accuracy"
accuracy that ignores class sizes balanced_accuracy_score "balanced_accuracy"
how many flagged cases are real precision_score "precision"
how many real cases were caught recall_score "recall"
one number for precision and recall f1_score, fbeta_score(beta=2) "f1"
one balanced number for all four cells matthews_corrcoef "matthews_corrcoef"
ranking quality, balanced classes roc_auc_score(y, proba) "roc_auc"
ranking quality, rare positives average_precision_score(y, proba) "average_precision"
the quality of probabilities log_loss, brier_score_loss "neg_log_loss", "neg_brier_score"
check calibration by eye CalibrationDisplay.from_predictions(y, proba)
the confusion matrix confusion_matrix(y, pred)
all per-class metrics classification_report(y, pred)
macro F1 for multiclass f1_score(y, pred, average="macro") "f1_macro"
precision in the top k sort by score, mean of the top k labels a custom function
ranking with graded relevance ndcg_score
the best threshold for a metric or a cost TunedThresholdClassifierCV(model, scoring=...)
a forecast error that is scale-free MASE: MAE ÷ seasonal naive MAE a custom function
cluster quality without labels silhouette_score, davies_bouldin_score
agreement with known groups adjusted_rand_score
a metric for model selection cross_val_score(model, X, y, scoring="...")
list every scoring string sklearn.metrics.get_scorer_names()
Metric Formula Function Units Misleads when
MAE 1n∑∣y−y^∣\frac{1}{n}\sum \lvert y - \hat y \rvert mean_absolute_error target a few big misses matter much more than many small ones
RMSE 1n∑(y−y^)2\sqrt{\frac{1}{n}\sum (y - \hat y)^2} root_mean_squared_error target a few outliers dominate the score
R² 1−∑(y−y^)2∑(y−yˉ)21 - \frac{\sum (y - \hat y)^2}{\sum (y - \bar y)^2} r2_score none you compare different test sets or target scales; a high R² still allows large errors
MAPE 1n∑∣y−y^y∣\frac{1}{n}\sum \left\lvert \frac{y - \hat y}{y} \right\rvert mean_absolute_percentage_error fraction some y are near 0; it favors under-forecasts
sMAPE 1n∑2∣y−y^∣∣y∣+∣y^∣\frac{1}{n}\sum \frac{2\lvert y - \hat y \rvert}{\lvert y \rvert + \lvert \hat y \rvert} by hand fraction (0–2) both y and the forecast are near 0
WAPE ∑∣y−y^∣∑∣y∣\frac{\sum \lvert y - \hat y \rvert}{\sum \lvert y \rvert} by hand fraction the total is dominated by a few big items
RMSLE RMSE of log⁡(1+y)\log(1 + y) root_mean_squared_log_error log ratio y can be negative
Median AE median∣y−y^∣\text{median} \lvert y - \hat y \rvert median_absolute_error target big misses matter: it ignores them
Pinball loss asymmetric absolute error at quantile α mean_pinball_loss target you need a point forecast, not a quantile

MAE is minimized by predicting the median; RMSE by predicting the mean. Choose the one that matches the number you want to predict.

import numpy as np
from sklearn.metrics import (
mean_absolute_error,
mean_absolute_percentage_error,
root_mean_squared_error,
)
y_true = np.array([120, 95, 140, 110, 3]) # the last item sells very little
cases = {
"small misses": np.array([115, 100, 150, 108, 9]),
"one big miss": np.array([115, 100, 150, 50, 3]),
}
for name, y_pred in cases.items():
print(f"{name:<13} MAE {mean_absolute_error(y_true, y_pred):5.1f} "
f"RMSE {root_mean_squared_error(y_true, y_pred):5.1f} "
f"MAPE {mean_absolute_percentage_error(y_true, y_pred):6.1%}")
Output
small misses MAE 5.6 RMSE 6.2 MAPE 43.7%
one big miss MAE 16.0 RMSE 27.4 MAPE 14.2%

In the first case, a 6-unit miss on the item that sells 3 makes MAPE 44%. In the second case, one 60-unit miss makes RMSE 1.7 times the MAE, while MAPE looks fine.

Metric Formula Function Misleads when
Accuracy TP+TNn\frac{TP + TN}{n} accuracy_score classes are imbalanced: “always no” scores high
Precision TPTP+FP\frac{TP}{TP + FP} precision_score read alone: flag one sure case and it is 1.0
Recall (sensitivity, TPR) TPTP+FN\frac{TP}{TP + FN} recall_score read alone: flag everything and it is 1.0
Specificity (TNR) TNTN+FP\frac{TN}{TN + FP} recall_score(y, pred, pos_label=0) positives are what matter
F1 2PRP+R\frac{2PR}{P + R} f1_score FP and FN costs differ; true negatives are ignored
F-beta (1+β2)PRβ2P+R\frac{(1+\beta^2)PR}{\beta^2 P + R} fbeta_score(beta=2) β is chosen without a cost argument
Balanced accuracy mean recall per class balanced_accuracy_score one class matters far more
MCC correlation of labels and predictions matthews_corrcoef stakeholders need an intuitive number
ROC-AUC P(score of a random positive > a random negative) roc_auc_score positives are rare: many false positives still give a high AUC
Average precision (PR-AUC) area under the precision–recall curve average_precision_score compared across data with different positive rates
Log loss −1n∑[ylog⁡p+(1−y)log⁡(1−p)]-\frac{1}{n}\sum [y \log p + (1-y)\log(1-p)] log_loss a few confident mistakes blow it up
Brier score 1n∑(p−y)2\frac{1}{n}\sum (p - y)^2 brier_score_loss positives are very rare (it stays small anyway)
Precision at k share of positives in the top k scores by hand k does not match the real capacity

ROC-AUC and average precision need scores (predict_proba(X)[:, 1] or decision_function), never 0/1 labels. Threshold metrics (precision, recall, F1) depend on the threshold; predict uses 0.5.

from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
accuracy_score,
average_precision_score,
balanced_accuracy_score,
recall_score,
roc_auc_score,
)
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=4000, n_features=10, n_informative=4,
weights=[0.95], flip_y=0.01, class_sep=0.8,
random_state=42)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, stratify=y,
random_state=42)
print(f"positive share {y_te.mean():.3f}")
models = {"always 0": DummyClassifier(), "logistic": LogisticRegression()}
for name, model in models.items():
model.fit(X_tr, y_tr)
pred, proba = model.predict(X_te), model.predict_proba(X_te)[:, 1]
print(f"{name:<9} acc {accuracy_score(y_te, pred):.3f}"
f" bal-acc {balanced_accuracy_score(y_te, pred):.3f}"
f" recall {recall_score(y_te, pred, zero_division=0):.3f}"
f" AP {average_precision_score(y_te, proba):.3f}"
f" AUC {roc_auc_score(y_te, proba):.3f}")
Output
positive share 0.053
always 0 acc 0.947 bal-acc 0.500 recall 0.000 AP 0.053 AUC 0.500
logistic acc 0.949 bal-acc 0.523 recall 0.047 AP 0.307 AUC 0.708

Both models reach 95% accuracy, and at the default threshold of 0.5 the logistic model catches almost no positives. The ranking metrics show the difference: AP rises from the positive share (0.053) to 0.307. The model is useful, but only with a lower threshold.

Suppose every flagged customer gets a retention offer that costs 10, and the offer keeps a churner who would otherwise cost 100. A flagged row costs 10 whether it is a true or a false positive; a missed churner costs 100. Flag a customer when the expected saving beats the offer: p×100>10p \times 100 > 10. The break-even threshold for calibrated probabilities is cost of the actionvalue of a caught positive=10100=0.10\frac{\text{cost of the action}}{\text{value of a caught positive}} = \frac{10}{100} = 0.10:

for threshold in [0.5, 0.3, 0.2, 0.1, 0.05]:
flag = proba >= threshold
fp = int(np.sum(flag & (y_te == 0)))
fn = int(np.sum(~flag & (y_te == 1)))
print(f"threshold {threshold:<4} flagged {flag.sum():>4} FP {fp:>4} FN {fn:>3}"
f" cost {10 * flag.sum() + 100 * fn:>6,}") # offers + lost churners
Output
threshold 0.5 flagged 5 FP 0 FN 102 cost 10,250
threshold 0.3 flagged 18 FP 4 FN 93 cost 9,480
threshold 0.2 flagged 40 FP 19 FN 86 cost 9,000
threshold 0.1 flagged 198 FP 150 FN 59 cost 7,880
threshold 0.05 flagged 767 FP 695 FN 35 cost 11,170

The cost is lowest near the break-even threshold. In practice, tune it with TunedThresholdClassifierCV(model, scoring=make_scorer(profit)) on training data, never on the test set.

When the team can call only k customers, judge the model by the share of positives among its top k scores:

order = np.argsort(-proba, kind="stable") # highest scores first
for k in [50, 100, 200]:
print(f"precision at {k:>3}: {y_te[order[:k]].mean():.2f} "
f"(random: {y_te.mean():.2f})")
Output
precision at 50: 0.48 (random: 0.05)
precision at 100: 0.34 (random: 0.05)
precision at 200: 0.24 (random: 0.05)
from sklearn.metrics import f1_score
y_true_mc = ["A"] * 8 + ["B", "C"]
y_pred_mc = ["A"] * 10 # always predicts the majority class
for avg in ["micro", "macro", "weighted"]:
score = f1_score(y_true_mc, y_pred_mc, average=avg, zero_division=0)
print(f"{avg:<8} F1 {score:.3f}")
Output
micro F1 0.800
macro F1 0.296
weighted F1 0.711
Average How Use when
micro pool all TP, FP, FN; equals accuracy for single-label data overall correctness
macro mean of the per-class scores every class matters equally (rare classes too)
weighted per-class scores weighted by class size reporting; it hides weak rare classes
Task Business goal Metric Why
churn call the 500 riskiest customers each month precision at 500, lift the capacity is fixed
churn offers cost 10, a lost customer 100 expected cost at a tuned threshold the costs are known
fraud review 1% of transactions, catch as much as possible recall at a 1% alert rate analysts are the bottleneck
fraud compare models before a threshold exists average precision rare positives
medical screening miss almost no cases recall at a specificity floor (or the reverse) a FN is far worse than a FP
spam filter never lose a real email recall at a fixed low FPR (for example 0.1%), or at a precision floor a FP (a real email in spam) is far worse
credit risk, insurance prices depend on the probability log loss, Brier, calibration curve the probabilities feed money
response targeting rank who is most likely to buy ROC-AUC, gains curve only the order of the response matters
marketing uplift rank who changes behavior because of the offer Qini curve, uplift curve (area under it) on a randomized treatment/control holdout a response model ranks “sure things” first: high AUC, zero uplift
house prices be within 10% of the sale price share within ±10%, MAPE the error is judged relative to price
demand forecast under-stocking costs more than over-stocking pinball loss at α = 0.9 an asymmetric cost
demand forecast compare series of different sizes MASE, WAPE scale-free
revenue forecast totals in money matter MAE, WAPE the errors add up in money
search, recommendations the best items first NDCG, precision at k graded relevance, top positions
customer segments groups that are distinct and usable silhouette plus business review there are no labels
Metric Formula or function Note
MAE, RMSE as above, on the backtest windows report per horizon (1 day, 7 days, 28 days)
MASE MAE ÷ in-sample seasonal naive MAE below 1 beats the seasonal naive forecast; works with zeros
sMAPE see the table above 0 to 200%
interval coverage share of actuals inside the 95% interval should be close to 95%
silhouette_score(X, labels) −1 to 1 separation; about 0.2 is normal for behavior data
davies_bouldin_score(X, labels) ≥ 0, lower is better compactness vs separation
adjusted_rand_score(a, b) about 0 (random) to 1 agreement with labels or another clustering; ignores label names
Trap Symptom Fix
accuracy on imbalanced classes 95% for a model that predicts “no” balanced accuracy, AP, recall at a fixed precision
ROC-AUC or AP on 0/1 predictions a much lower, odd score pass predict_proba(X)[:, 1]
metric(y_pred, y_true) wrong values (R², precision and recall are not symmetric) metric(y_true, y_pred)
scoring="neg_..." negative numbers; “max” means the smallest error flip the sign before you report
mean_squared_error(..., squared=False) TypeError (removed in scikit-learn 1.6) root_mean_squared_error
MAPE with y near 0 a huge percentage from tiny items WAPE, MASE or MAE
mean_absolute_percentage_error read as a percent 0.12 shown as “0.12%” it is a fraction: format with :.1%
R² compared across test sets a “better” model on an easier split compare on the same split; report MAE too
a log-target model scored on the log scale errors look tiny back-transform before scoring: np.expm1 after np.log1p (np.exp after np.log), or TransformedTargetRegressor(func=np.log1p, inverse_func=np.expm1)
F1 when costs are known the wrong threshold expected cost or profit
threshold tuned on the test set an optimistic score TunedThresholdClassifierCV on training data
precision with no positive predictions UndefinedMetricWarning zero_division=0, and check the threshold
class weights or resampling probabilities shift upward judge log loss and Brier after calibration
weighted average in multiclass weak rare classes are hidden macro, plus the per-class report
silhouette as the only cluster check “best k” that nobody can use profile the clusters; check stability with ARI
one score without spread a lucky split looks like progress CV mean ± std, or a paired comparison

Cross-validation estimates how a model will score on data it has not seen. That estimate is honest only if each validation fold looks like the future data relative to its training folds. If the model will meet new customers, new stores or next month, the folds must hold out whole customers, whole stores or later dates. This guide maps the shape of the data to a scikit-learn splitter and lists the leaks that inflate scores.

flowchart TD
    A{"Ordered in time,<br/>predict the future?"} -->|yes| T["TimeSeriesSplit<br/>test_size = horizon, gap"]
    A -->|no| B{"Several rows per customer,<br/>store or patient?"}
    B -->|yes| B1{"Rare class?"}
    B1 -->|yes| SG["StratifiedGroupKFold"]
    B1 -->|no| G{"Fewer than<br/>about 20 groups?"}
    G -->|yes| LOGO["LeaveOneGroupOut"]
    G -->|no| GK["GroupKFold"]
    B -->|no| C{"Classification?"}
    C -->|yes| S["StratifiedKFold"]
    C -->|no| K["KFold, shuffle=True"]
    S --> N{"Under about<br/>1,000 rows?"}
    K --> N
    N -->|yes| R["RepeatedStratifiedKFold /<br/>RepeatedKFold"]
    N -->|no| F["5 folds"]

If you also tune hyperparameters, the tuning needs its own inner splitter: nested cross-validation (see below).

I want to… Use… Notes
one hold-out test set train_test_split(X, y, test_size=0.2, random_state=42) add stratify=y for classification
a hold-out set for time data X.iloc[:-n], X.iloc[-n:] on rows sorted by time never shuffle
a hold-out set by group GroupShuffleSplit(n_splits=1, test_size=0.2) next(gss.split(X, y, groups))
k folds of independent rows (regression) KFold(n_splits=5, shuffle=True, random_state=42)
keep class shares in every fold StratifiedKFold(n_splits=5, shuffle=True, random_state=42) the default for classifiers with cv=5 (no shuffle)
keep all rows of a customer together GroupKFold(n_splits=5) pass groups=
groups and a rare class StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=42)
one fold per store, site or hospital LeaveOneGroupOut() for few, large groups
train on the past, test on the future TimeSeriesSplit(n_splits=5, test_size=h) rows sorted by time
a delay between data and prediction TimeSeriesSplit(..., gap=g) skips g rows between train and test
a sliding training window TimeSeriesSplit(..., max_train_size=w) when old data is stale
a steadier estimate on small data RepeatedStratifiedKFold(n_splits=5, n_repeats=10) 50 fits
leave one row out LeaveOneOut() very small data only; high variance
custom folds (a fixed validation period) PredefinedSplit(test_fold) −1 = always in training
scores for any splitter cross_val_score(model, X, y, cv=splitter, groups=g)
several metrics and fit times cross_validate(model, X, y, cv=..., scoring=[...]) return_train_score=True for overfitting
out-of-fold predictions cross_val_predict(model, X, y, cv=...) for plots and stacking, not for a score
tune without leaking into the estimate cross_val_score(GridSearchCV(model, grid, cv=inner), X, y, cv=outer) nested CV
groups inside a search search.fit(X, y, groups=g) with a group splitter as cv
groups at both levels of nested CV sklearn.set_config(enable_metadata_routing=True), then cross_val_score(search, X, y, cv=GroupKFold(5), params={"groups": g}) see below
preprocessing inside each fold make_pipeline(preprocess, model) the whole pipeline goes into CV
resampling inside each fold imblearn.pipeline.make_pipeline(SMOTE(), model) never resample before the split
a threshold chosen without the test set TunedThresholdClassifierCV(model, cv=...)
see the folds for tr, te in splitter.split(X, y, groups): ... check sizes, dates, groups
Data shape Splitter Why Leakage risk if you use plain KFold
independent rows, regression KFold(5, shuffle=True) rows are exchangeable low; shuffle in case the file is sorted
independent rows, classification StratifiedKFold(5, shuffle=True) every fold has the class shares of the data folds without positives on small or rare data
imbalanced classes (1–10% positive) StratifiedKFold, plus AP or recall as the metric stable positive counts per fold a fold with 0 positives gives undefined scores
several rows per entity, new entities later GroupKFold the model must generalize to unseen entities memorizes entities; scores far too high
groups and a rare class StratifiedGroupKFold both at once, as far as possible as above
few large groups (12 stores, 5 hospitals) LeaveOneGroupOut “does it work at a new site?” site effects leak
time series, forecasting TimeSeriesSplit(test_size=h, gap=g) the past predicts the future the model interpolates between future and past days
events with a delay (labels known 30 days later) TimeSeriesSplit(gap=30) the gap mimics the delay the latest training labels would not exist yet
panel data: many series over time split by date, and by series when new series appear both kinds of leakage trends and series identity leak
small data (under about 1,000 rows) RepeatedStratifiedKFold / RepeatedKFold averages out the luck of one split high variance, not leakage
tuning and reporting together nested CV: inner search, outer evaluation best_score_ is biased upward an optimistic final score
duplicated or near-duplicate rows deduplicate, or group by the duplicate key copies land on both sides of a split memorized copies inflate the score
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import (
GroupKFold,
KFold,
StratifiedKFold,
TimeSeriesSplit,
cross_val_score,
)
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
y_small = np.r_[np.ones(10, dtype=int), np.zeros(90, dtype=int)] # sorted file
X_small = np.zeros((100, 1))
splitters = {
"KFold": KFold(5),
"KFold shuffled": KFold(5, shuffle=True, random_state=0),
"StratifiedKFold": StratifiedKFold(5, shuffle=True, random_state=0),
}
for name, splitter in splitters.items():
positives = [int(y_small[te].sum()) for _, te in splitter.split(X_small, y_small)]
print(f"{name:<16} positives per fold {positives}")
Output
KFold positives per fold [10, 0, 0, 0, 0]
KFold shuffled positives per fold [3, 2, 4, 0, 1]
StratifiedKFold positives per fold [2, 2, 2, 2, 2]

Unshuffled KFold on a sorted file puts every positive in one fold. Shuffling helps but leaves a fold with none. StratifiedKFold gives each fold 2.

“Many rows per customer”: group the folds

Section titled ““Many rows per customer”: group the folds”

Here each customer has 8 rows with similar features and one label. The label is random per customer, so no model can predict it for a new customer: the honest score is 50%.

rng = np.random.default_rng(42)
n_customers, rows_each = 100, 8
customer = np.repeat(np.arange(n_customers), rows_each)
centers = rng.normal(size=(n_customers, 4))
X_grp = centers[customer] + rng.normal(scale=0.3, size=(len(customer), 4))
y_grp = rng.integers(0, 2, n_customers)[customer] # one random label per customer
knn = KNeighborsClassifier(n_neighbors=5)
kf = cross_val_score(knn, X_grp, y_grp, cv=KFold(5, shuffle=True, random_state=42))
gkf = cross_val_score(knn, X_grp, y_grp, groups=customer,
cv=GroupKFold(5, shuffle=True, random_state=42))
print(f"KFold {kf.mean():.2f} GroupKFold {gkf.mean():.2f}")
Output
KFold 0.80 GroupKFold 0.50

KFold puts rows of the same customer in training and validation, so the model recognizes customers instead of learning a pattern. GroupKFold gives the true answer.

“Forecast daily visits”: split by time

Section titled ““Forecast daily visits”: split by time”

A random forest on a time index, the weekday and the month. Random folds let it interpolate between neighboring days; time-ordered folds make it forecast:

traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"])
traffic["visits"] = traffic["visits"].interpolate() # 5 tracking outages
X_ts = pd.DataFrame({
"t": np.arange(len(traffic)),
"dow": traffic["date"].dt.day_of_week,
"month": traffic["date"].dt.month,
})
forest = RandomForestRegressor(n_estimators=100, random_state=42)
for name, cv in {
"KFold shuffled": KFold(5, shuffle=True, random_state=42),
"TimeSeriesSplit": TimeSeriesSplit(n_splits=5, test_size=90),
}.items():
mae = -cross_val_score(forest, X_ts, traffic["visits"], cv=cv,
scoring="neg_mean_absolute_error").mean()
print(f"{name:<16} MAE {mae:,.0f} visits")
Output
KFold shuffled MAE 319 visits
TimeSeriesSplit MAE 771 visits

The shuffled estimate is less than half the real forecasting error. Set test_size to the forecast horizon and gap to the delay before data arrives:

splitter = TimeSeriesSplit(n_splits=3, test_size=28, gap=7)
for train_idx, test_idx in splitter.split(traffic):
dates = traffic["date"]
print(f"train to {dates[train_idx[-1]]:%Y-%m-%d} ({len(train_idx)} days), "
f"test {dates[test_idx[0]]:%Y-%m-%d} to {dates[test_idx[-1]]:%Y-%m-%d}")
Output
train to 2024-10-01 (1005 days), test 2024-10-09 to 2024-11-05
train to 2024-10-29 (1033 days), test 2024-11-06 to 2024-12-03
train to 2024-11-26 (1061 days), test 2024-12-04 to 2024-12-31

“Select features, then cross-validate”: the classic leak

Section titled ““Select features, then cross-validate”: the classic leak”

Random features and random labels: the honest accuracy is 50%. Selecting the 20 “best” features on all rows before CV lets the selector see the validation labels:

X_rand = rng.normal(size=(200, 1000))
y_rand = rng.permutation(np.repeat([0, 1], 100))
folds = StratifiedKFold(5, shuffle=True, random_state=42)
X_selected = SelectKBest(f_classif, k=20).fit_transform(X_rand, y_rand) # all rows
leaky = cross_val_score(LogisticRegression(), X_selected, y_rand, cv=folds)
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
honest = cross_val_score(pipe, X_rand, y_rand, cv=folds) # selects inside each fold
print(f"leaky {leaky.mean():.2f} honest {honest.mean():.2f}")
Output
leaky 0.75 honest 0.48

The inner splitter tunes; the outer splitter scores the whole “tune, then refit” procedure. Use the same kind of splitter at both levels (groups or time if the data need them; groups need one extra setting, shown after this example):

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
X_bc, y_bc = load_breast_cancer(return_X_y=True)
inner = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
search = GridSearchCV(DecisionTreeClassifier(random_state=42),
{"max_depth": [2, 3, 4, 6]}, cv=inner)
nested = cross_val_score(search, X_bc, y_bc, cv=outer)
best = search.fit(X_bc, y_bc).best_score_ # the search on all rows: the shipped model
print(f"nested {nested.mean():.3f} best_score_ {best:.3f}")
Output
nested 0.912 best_score_ 0.935

Report the nested estimate. best_score_ is the maximum of several noisy scores, so it tends to be optimistic.

With groups, both levels need them. cross_val_score(..., groups=g) passes the groups to the outer splitter only, so every inner GroupKFold gets groups=None and all fits fail. Turn on metadata routing and pass the groups as params; scikit-learn then routes them to the inner splitter too. Here with the customer data from above, where the honest score is 50%:

import sklearn
sklearn.set_config(enable_metadata_routing=True) # route groups to the inner search
grouped_search = GridSearchCV(KNeighborsClassifier(), {"n_neighbors": [5, 15]},
cv=GroupKFold(3))
nested_grp = cross_val_score(grouped_search, X_grp, y_grp, cv=GroupKFold(5),
params={"groups": customer})
sklearn.set_config(enable_metadata_routing=False) # back to the default
print(f"grouped nested CV {nested_grp.mean():.2f}")
Output
grouped nested CV 0.48

Time series need no routing: TimeSeriesSplit uses the row order, so GridSearchCV(..., cv=TimeSeriesSplit()) inside cross_val_score(..., cv=TimeSeriesSplit()) works as written.

Leak Example Symptom Fix
preprocessing on all rows StandardScaler().fit(X) before CV slightly optimistic scores put every learned step in a Pipeline
feature selection on all rows SelectKBest().fit(X, y) before CV random data scores far above chance selector inside the pipeline
target encoding on all rows groupby(cat)[y].mean() mapped onto training rows high-cardinality columns look magical TargetEncoder inside the pipeline
resampling before the split SMOTE().fit_resample(X, y), then CV recall and F1 far too high imblearn.pipeline.Pipeline
shared entities across folds the same customer in train and validation score drops in production GroupKFold
random folds on time data KFold(shuffle=True) on daily data the backtest beats production by far TimeSeriesSplit
future information in features rolling(7, center=True), bfill(), totals over the whole period a perfect-looking backtest shift(1) before rolling; features known at prediction time only
a label delay ignored the last week’s labels not yet known in production the model relies on very fresh data gap= in TimeSeriesSplit
post-outcome columns a “cancellation reason” for churn one feature explains everything drop columns created after the outcome
duplicates across the split the same review twice inflated text-classification scores deduplicate before the split
tuning on the test set choosing the threshold or model by test score a test score you cannot reproduce choose with CV; look at the test set once
reporting best_score_ the maximum over many candidates optimistic by a few points nested CV or a fresh test set
Trap Symptom Fix
nested CV with a group splitter inside all fits fail: the inner groups is None metadata routing and params={"groups": g}
groups= with KFold or StratifiedKFold ignored, with a warning a group splitter
cv=5 with a classifier StratifiedKFold without shuffling pass StratifiedKFold(5, shuffle=True, random_state=42)
cv=5 with a regressor on a sorted file each fold holds one range of the target KFold(5, shuffle=True, random_state=42)
TimeSeriesSplit on unsorted rows folds mix past and future sort by time first
TimeSeriesSplit on panel data with one row per series per day test days overlap training days of other series split on unique dates, then select rows
shuffle=True without random_state different scores on every run random_state=42
GroupKFold(shuffle=True) TypeError on old versions scikit-learn 1.6 or newer
a single train/test split on small data the score depends on the seed repeated CV, report mean ± std
LeaveOneOut for model selection slow and noisy 5 or 10 folds, repeated
comparing models on different folds differences come from the splits the same splitter object (fixed seed) for all models
cross_val_predict scored as a whole not the same as the mean fold score use it for plots; report cross_val_score
standard deviation of fold scores read as a CI the training sets overlap, so the fold scores are correlated and the spread understates the uncertainty treat it as a rough spread
the search refit forgotten the best parameters, but no fitted model refit=True (default), then search.best_estimator_

pandas, Polars and DuckDB all transform tables. They differ in how they run: pandas is eager and mostly single-core; Polars plans queries and uses every core; DuckDB is a SQL engine inside your Python process that reads files and DataFrames directly. They also pass data to each other cheaply, so one project often uses two of them. This guide helps you choose, then shows the same tasks in all three. The examples use data/sales.csv (20,228 order lines) and data/stores.csv.

flowchart TD
    A{"Where is the data?"} -->|"in a database server"| SQL["SQL in that database:<br/>move the work to the data"]
    A -->|"files or DataFrames"| B{"Fits easily in memory?"}
    B -->|no| C{"Prefer SQL?"}
    C -->|yes| D1["DuckDB on the files"]
    C -->|no| D2["Polars lazy, streaming"]
    B -->|yes| E{"Next step needs pandas?<br/>plots, statsmodels"}
    E -->|yes| P["pandas"]
    E -->|no| F{"Speed or a long<br/>pipeline matters?"}
    F -->|yes| PL["Polars, or DuckDB for SQL"]
    F -->|no| P
I want to… Use… Example
explore a small table and plot it pandas df.groupby("region")["revenue"].sum().plot.bar()
feed statsmodels, seaborn or an old tutorial pandas smf.ols("y ~ x", data=df)
a fast pipeline over large CSV or Parquet files Polars lazy pl.scan_parquet("data/*.parquet").filter(...).collect()
data larger than memory, in Python code Polars streaming lf.collect(engine="streaming")
data larger than memory, in SQL DuckDB duckdb.sql("SELECT ... FROM 'data/*.parquet'")
query a CSV file without loading it first DuckDB duckdb.sql("SELECT COUNT(*) FROM 'data/sales.csv'")
run SQL on a pandas or Polars frame DuckDB duckdb.sql("SELECT ... FROM df"): the variable name is the table
run SQL inside Polars df.sql(...) df.sql("SELECT region, SUM(revenue) FROM self GROUP BY region")
read from SQLite or PostgreSQL pd.read_sql_query, pl.read_database push filters and joins into the SQL
one row per group (top 1) pandas head(1) after sort; Polars over; SQL QUALIFY see task 3
a group total on every row transform; .over(); SUM() OVER see the translation table
monthly totals resample("MS"); dt.truncate("1mo"); date_trunc('month', d) see task 4
strict, explicit dtypes Polars or DuckDB errors instead of silent casts
row labels, .loc, MultiIndex pandas Polars and SQL have no index
time series with a DatetimeIndex pandas asfreq, resample, rolling("7D")
a long ETL job with many steps Polars lazy one optimized plan
ad hoc questions by an SQL-minded team DuckDB the query is the documentation
convert pandas → Polars pl.from_pandas(df) needs pyarrow
convert Polars → pandas df.to_pandas() needs pyarrow
a DuckDB result as pandas / Polars rel.df() / rel.pl()
scikit-learn output as Polars set_output(transform="polars") before fit
NumPy for a model df.to_numpy() all three can hand over arrays
pandas 3 Polars 2 DuckDB 2 (SQL)
Execution eager: each line runs at once eager, or lazy with a query optimizer a planned SQL query
Cores mostly one all all
Memory the whole frame in RAM; intermediate copies Arrow columns; streaming engine for larger than RAM columnar; spills to disk when RAM runs out
Syntax methods, [], .loc, the index expressions: pl.col("x").sum().over("g") SQL: SUM(x) OVER (PARTITION BY g)
Row labels an index (often a source of bugs) none none
Missing values NaN, NA; integers become floats in some operations null, separate from NaN NULL, three-valued logic
Strings str dtype (Arrow-backed) String (Arrow) VARCHAR
Types flexible, some silent casts strict; errors on mismatch strict
Files read into memory read_* or lazy scan_* (CSV, Parquet, NDJSON) queries CSV, Parquet, JSON and globs in place
Ecosystem everywhere: Matplotlib, seaborn, statsmodels, scikit-learn growing; converts to pandas cheaply any tool that speaks SQL; returns pandas or Polars
Best for small to medium data, exploration, plots, time series pipelines on large files, ETL, speed ad hoc analysis on files, joins, Parquet folders, SQL teams
Weak at speed and memory on large data; row loops niche operations, fewer tutorials step-by-step row logic, complex reshaping

Rough sizes: pandas is comfortable up to a few million rows (under about a fifth of your RAM). Polars and DuckDB stay fast to hundreds of millions of rows, and both can work through data larger than memory.

import duckdb
import pandas as pd
import polars as pl
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
pl.Config.set_tbl_width_chars(100)
pl.Config.set_tbl_hide_column_data_types(True)
sales_pd = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
stores_pd = pd.read_csv("data/stores.csv")
sales_pl = pl.read_csv("data/sales.csv", try_parse_dates=True)
stores_pl = pl.read_csv("data/stores.csv")

DuckDB reads the CSV files directly by path. It could also query sales_pd or sales_pl by their variable names.

Orders and revenue per region and channel, the four largest:

task1 = (
sales_pd.groupby(["region", "channel"], as_index=False)
.agg(orders=("order_id", "count"), revenue=("revenue", "sum"))
.sort_values("revenue", ascending=False)
.head(4)
)
print(task1)
Output
region channel orders revenue
1 East store 3119 567352.79
3 North store 2822 510539.53
5 South store 3021 508161.62
7 West store 2771 491003.42

2024 revenue per city (from the stores table), top 3:

task2 = (
sales_pd[sales_pd["order_date"].dt.year == 2024]
.merge(stores_pd[["store_id", "city"]], on="store_id", how="left")
.groupby("city", as_index=False)["revenue"].sum()
.nlargest(3, "revenue")
)
print(task2)
Output
city revenue
8 New York 263924.00
2 Chicago 220899.08
11 Seattle 213238.50

The best-selling product of each category by revenue, a window-function task:

per_product = sales_pd.groupby(["category", "product"], as_index=False)["revenue"].sum()
task3 = (
per_product.sort_values(["category", "revenue"], ascending=[True, False])
.groupby("category")
.head(1) # first row of each group after the sort
)
print(task3.to_string(index=False))
Output
category product revenue
Beauty Electric Toothbrush 43618.57
Books Statistics Made Simple 31270.35
Clothing Waterproof Rain Jacket 104660.50
Electronics 14-inch Ultrabook Laptop 665328.45
Home Espresso Machine 197987.70
Sports Adjustable Dumbbells 165084.30

Task 4: monthly totals and the change from the previous month

Section titled “Task 4: monthly totals and the change from the previous month”

The first four months of 2024:

monthly = sales_pd.set_index("order_date")["revenue"].resample("MS").sum()
task4 = pd.DataFrame({"revenue": monthly, "change": monthly.pct_change()})
print(task4.loc["2024-01":"2024-04"].round(3))
Output
revenue change
order_date
2024-01-01 119596.89 -0.504
2024-02-01 106320.41 -0.111
2024-03-01 145567.22 0.369
2024-04-01 114917.50 -0.211

Polars’ lazy API and DuckDB both read only the columns and rows a query needs. pandas reads the whole file unless you say otherwise:

lazy = (
pl.scan_csv("data/sales.csv") # nothing is read yet
.filter(pl.col("channel") == "online")
.group_by("category")
.agg(pl.col("revenue").sum().round(2))
.sort("revenue", descending=True)
)
print(lazy.head(2).collect()) # the optimizer reads only 3 columns
online = duckdb.sql("""
SELECT COUNT(*) FROM 'data/sales.csv' WHERE channel = 'online'
""").fetchall()
print(online)
cols = pd.read_csv("data/sales.csv", usecols=["channel", "revenue"]) # pandas: by hand
print(cols.shape)
Output
shape: (2, 2)
┌─────────────┬───────────┐
│ category ┆ revenue │
╞═════════════╪═══════════╡
│ Electronics ┆ 767072.48 │
│ Home ┆ 284066.0 │
└─────────────┴───────────┘
[(8495,)]
(20228, 2)
Tool Larger than memory
pandas read_csv(..., chunksize=100_000) and combine partial results by hand; or switch tools
Polars pl.scan_csv / pl.scan_parquet, then collect(engine="streaming") or sink_parquet(...)
DuckDB queries files in place; spills to disk; COPY (SELECT ...) TO 'out.parquet'
Task pandas Polars SQL (DuckDB)
select columns df[["a", "b"]] df.select("a", "b") SELECT a, b
filter rows df[df["a"] > 5], df.query("a > 5") df.filter(pl.col("a") > 5) WHERE a > 5
new column df.assign(c=df["a"] * 2) df.with_columns(c=pl.col("a") * 2) SELECT *, a * 2 AS c
if/else column np.where(cond, x, y) pl.when(cond).then(x).otherwise(y) CASE WHEN cond THEN x ELSE y END
sort df.sort_values("a", ascending=False) df.sort("a", descending=True) ORDER BY a DESC
group and aggregate df.groupby("g").agg(t=("x", "sum")) df.group_by("g").agg(t=pl.col("x").sum()) SELECT g, SUM(x) AS t ... GROUP BY g
count rows per group df.groupby("g").size() df.group_by("g").len() COUNT(*) ... GROUP BY g
filter groups filter the aggregated frame .filter(...) after agg HAVING COUNT(*) > 10
group total on each row df.groupby("g")["x"].transform("sum") pl.col("x").sum().over("g") SUM(x) OVER (PARTITION BY g)
rank in a group (ties share the lowest rank) df.groupby("g")["x"].rank(method="min", ascending=False) pl.col("x").rank("min", descending=True).over("g") RANK() OVER (PARTITION BY g ORDER BY x DESC)
previous row df.sort_values(["g", "d"]).groupby("g")["x"].shift() df.sort("g", "d"), then pl.col("x").shift().over("g") LAG(x) OVER (PARTITION BY g ORDER BY d)
running total df.sort_values(["g", "d"]).groupby("g")["x"].cumsum() df.sort("g", "d"), then pl.col("x").cum_sum().over("g") SUM(x) OVER (PARTITION BY g ORDER BY d ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
left join a.merge(b, on="k", how="left") a.join(b, on="k", how="left") a LEFT JOIN b USING (k)
rows without a match a[~a["k"].isin(b["k"])] a.join(b, on="k", how="anti") WHERE NOT EXISTS (...), ANTI JOIN
stack frames pd.concat([a, b]) pl.concat([a, b]) UNION ALL
distinct df.drop_duplicates() df.unique(maintain_order=True) SELECT DISTINCT
long to wide df.pivot_table(index="r", columns="c", values="v", aggfunc="sum") df.pivot(on="c", index="r", values="v", aggregate_function="sum") PIVOT t ON c USING SUM(v) GROUP BY r
wide to long df.melt(id_vars="k") df.unpivot(index="k") UNPIVOT t ON COLUMNS(* EXCLUDE (k))
fill missing df["x"].fillna(0) pl.col("x").fill_null(0) COALESCE(x, 0)
month of a date df["d"].dt.to_period("M") pl.col("d").dt.truncate("1mo") date_trunc('month', d)

pandas and Polars window operations follow the current row order, so sort first; SQL states the order in OVER. Without ROWS BETWEEN ..., SUM(x) OVER (... ORDER BY d) uses a RANGE frame: rows tied on d are added in one step, unlike cumsum.

From → to Code Cost
pandas → Polars pl.from_pandas(df) cheap for numeric columns (Arrow)
Polars → pandas df.to_pandas() cheap with pyarrow
pandas or Polars → DuckDB duckdb.sql("SELECT ... FROM df") no copy: DuckDB scans the frame
DuckDB → pandas / Polars .df() / .pl() one conversion of the result
SQLite → pandas / Polars pd.read_sql_query(sql, con), pl.read_database(sql, connection=con) the database does the filtering
any → NumPy df.to_numpy(), rel.fetchnumpy()
any → Parquet df.to_parquet(p), df.write_parquet(p), COPY ... TO 'p.parquet' the best format to share between tools

A common split: DuckDB or Polars to filter and aggregate the big data, then .to_pandas() on the small result for plots and statsmodels.

Trap Symptom Fix
a pandas result with a group index columns missing after groupby; odd joins as_index=False or reset_index()
pandas index alignment NaN after assigning a Series from another frame align on keys with merge, or use .to_numpy()
Polars group_by order the row order changes between runs .sort(...) or maintain_order=True
Polars top_k order not guaranteed to be sorted .sort(...).head(k)
pl.count() for rows TypeError in Polars 2 pl.len()
pandas tutorials in Polars AttributeError: groupby, melt removed group_by, unpivot; see the Polars page
NULL in SQL comparisons WHERE x <> 'a' drops NULL rows x IS DISTINCT FROM 'a', or COALESCE
NaN vs null in Polars fill_null does not touch NaN fill_nan(None) first, or fill_nan(0)
integer column with missing values in pandas it becomes float Int64 (nullable) dtype
duckdb.sql(...) treated as data a relation, not rows; fetchone() does not exist in DuckDB 2 .df(), .pl() or .fetchall()
DuckDB "text" in double quotes Binder Error: a column name single quotes for strings
integer division 7 / 2 is 3 in SQLite, 3.5 in DuckDB // in DuckDB; CAST in SQLite
to_pandas() or from_pandas() ModuleNotFoundError: pyarrow pip install pyarrow
row-by-row apply in pandas or map_elements in Polars 100× slower than an expression vectorized column expressions
collecting a huge lazy result out of memory at collect() aggregate first, or sink_parquet
benchmarks on tiny data pandas looks as fast as Polars measure on realistic sizes; choose for clarity on small data
string matching across tools LIKE is case-sensitive in DuckDB, not in SQLite ILIKE in DuckDB; .str.contains("x", case=False) in pandas

Most failed ML projects fail at a step, not at the model: a vague goal, a leaky split, no baseline or a test set used ten times. This page gives the whole workflow as a flowchart and a numbered checklist. Every step links to the module that teaches it and to the cheat sheet page with the code. A compact run of the steps in code follows the checklist.

flowchart TD
    A["1. Frame the problem"] --> B["2. Get and check the data"]
    B --> C["3. Split: lock the test set"]
    C --> D["4. Baseline"]
    D --> E["5. Features in a pipeline"]
    E --> F["6. CV, tuning,<br/>leak check"]
    F -->|"not good enough"| E
    F --> G["7. Evaluate once on test"]
    G -->|"fails: report it,<br/>new test set"| A
    G --> H["8. Interpret"]
    H --> I["9. Deploy"]
    I --> J["10. Monitor"]
    J -->|"drift or a drop"| B
I want to… Use… Page
turn a business question into a task target, unit of prediction, decision, metric Which metric
choose a model family the task, the data size, the need to explain Which ML algorithm
load and check the data df.info(), df.isna().mean(), df.describe() pandas
a hold-out test set train_test_split(X, y, test_size=0.2, stratify=y, random_state=42) scikit-learn API
a split for groups or time GroupShuffleSplit, a cut-off date Which CV strategy
a baseline to beat DummyClassifier(strategy="prior"), DummyRegressor() Models
a forecast baseline seasonal naive Time series
preprocessing without leakage Pipeline + ColumnTransformer Preprocessing
mixed column types OneHotEncoder(handle_unknown="ignore"), StandardScaler, SimpleImputer Preprocessing
a strong tabular model HistGradientBoostingClassifier, LightGBM Boosting
a score with an error bar cross_val_score(pipe, X, y, cv=StratifiedKFold(5, shuffle=True, random_state=42)) CV and tuning
the right CV splitter StratifiedKFold, GroupKFold, TimeSeriesSplit Which CV strategy
tune hyperparameters GridSearchCV, RandomizedSearchCV, Optuna CV and tuning
handle rare positives class_weight="balanced", a tuned threshold Metrics
an honest final score roc_auc_score(y_test, best.predict_proba(X_test)[:, 1]) (your chosen metric), once Metrics
curves and reports classification_report, ROC and PR curves Metrics
check for leaks before the test permutation_importance on validation or out-of-fold data Interpretability
what drives the final model coefficients, PDP, SHAP Interpretability
save the model with metadata joblib bundle + JSON sidecar Deployment
serve predictions FastAPI + pydantic Deployment
track experiments MLflow with sqlite:///mlflow.db Deployment
detect drift PSI and KS per feature Deployment
find groups without a target k-means, HDBSCAN Unsupervised learning
model text TfidfVectorizer in a pipeline NLP
a neural network PyTorch training loop PyTorch
  1. Frame the problem. Write the question as a prediction: the target, the unit (one row per customer, per day), the moment of prediction and the decision it drives. Choose the metric from the cost of each error, and a target value for it. Check that every feature is known at prediction time. Module: 34 scikit-learn workflow, 36 classification. Cheat sheet: Which metric, Which ML algorithm.
  2. Get and check the data. Load it, check dtypes, missing values, duplicates, ranges and the target balance. Explore with plots. Fingerprint the snapshot (SHA-256). Module: 26 data cleaning, 27 exploratory data analysis. Cheat sheet: pandas, Which chart.
  3. Split and lock the test set. Split before any fitting: stratified for classes, by group when rows share an entity, by time for time series. Do not look at the test set again until step 7. Module: 34 scikit-learn workflow, 37 model evaluation and tuning. Cheat sheet: Which CV strategy, scikit-learn API.
  4. Build a baseline. A dummy model, a simple rule or a seasonal naive forecast, then a simple linear model. Every later model must beat it by more than the CV spread. Module: 34 scikit-learn workflow, 35 regression. Cheat sheet: scikit-learn API, Models.
  5. Engineer features inside a pipeline. Imputation, scaling, encoding and feature creation go into a Pipeline with a ColumnTransformer, so every CV fold refits them. Module: 33 feature engineering, 34 scikit-learn workflow. Cheat sheet: Preprocessing.
  6. Cross-validate and tune. Compare model families with the same CV splitter, then tune the best one or two. Report the mean and the spread. Use learning curves to see whether more data or a bigger model helps. Check for leaks here, before the test: run permutation importance on validation or out-of-fold data, and drop any feature that is too good to be true. Module: 37 model evaluation and tuning, 38 ensembles. Cheat sheet: CV and tuning, Boosting, Models.
  7. Evaluate once on the test set. Refit the chosen pipeline on all training rows, score the test set once, and compare with the baseline and the goal from step 1. Choose the decision threshold on validation data, not on the test set. If you change the model after this step, the test set is used up: report that, or set aside a new one. Module: 36 classification, 37 model evaluation and tuning. Cheat sheet: Metrics.
  8. Interpret. Explain the final model: coefficients or SHAP for the main drivers, partial dependence for effects, SHAP for single predictions. This step explains; it makes no modeling decisions. Module: 43 interpretability. Cheat sheet: Interpretability.
  9. Deploy. Save the pipeline with its metadata (versions, features, metrics, threshold), load it with checks, serve it behind a validated API and test the API. Module: 44 ML in production. Cheat sheet: Deployment.
  10. Monitor. Watch service health, input quality, drift (PSI) and, when labels arrive, the metric. Retrain with the same script under a written rule, and keep the previous model for rollback. Module: 44 ML in production. Cheat sheet: Deployment.
Task Specific steps Module Cheat sheet
clustering, segmentation no target: steps 3 and 7 become stability checks and profiles 39 Unsupervised learning
forecasting split by time, seasonal naive baseline, TimeSeriesSplit 40 Time series
text the vectorizer is a pipeline step 41 NLP
neural networks a validation set for early stopping inside step 6 42 PyTorch

A compact run of steps 3 to 9 on data/customers.csv (churn). Each comment names the step.

import json
from pathlib import Path
import joblib
import numpy as np
import pandas as pd
import sklearn
from sklearn.base import clone
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.inspection import permutation_importance
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import (
GridSearchCV,
StratifiedKFold,
cross_val_score,
train_test_split,
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
customers = pd.read_csv("data/customers.csv")
categorical = ["plan", "contract", "payment_method"]
numeric = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
X, y = customers[categorical + numeric], customers["churned"]
# 3. Split once and lock the test set
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
# 4. Baseline
dummy = cross_val_score(DummyClassifier(), X_train, y_train, cv=cv, scoring="roc_auc")
# 5. Features in a pipeline
pipe = Pipeline([
("prep", ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
("num", StandardScaler(), numeric),
])),
("model", LogisticRegression(max_iter=1000)),
])
# 6. Cross-validate and tune on the training rows only
search = GridSearchCV(pipe, {"model__C": [0.01, 0.1, 1.0]}, cv=cv, scoring="roc_auc")
search.fit(X_train, y_train)
spread = search.cv_results_["std_test_score"][search.best_index_]
print(f"baseline CV AUC {dummy.mean():.3f}")
print(f"best {search.best_params_} CV AUC {search.best_score_:.3f} ± {spread:.3f}")
# 6. Leak check before the test: permutation importance on a validation split
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=42
)
check = clone(search.best_estimator_).fit(X_fit, y_fit)
perm = permutation_importance(check, X_val, y_val, scoring="roc_auc",
n_repeats=5, random_state=42)
top = pd.Series(perm.importances_mean, index=X.columns).nlargest(3)
print(top.round(3).to_dict()) # no single column dominates: no obvious leak
# 7. Evaluate once on the test set: no decisions after this line
best = search.best_estimator_ # refitted on all training rows
test_auc = roc_auc_score(y_test, best.predict_proba(X_test)[:, 1])
print(f"test AUC {test_auc:.3f}")
# 8. Interpret the final model: odds ratios of its coefficients
odds = pd.Series(np.exp(best[-1].coef_[0]), index=best[0].get_feature_names_out())
print(odds.sort_values().iloc[[0, -1]].round(2).to_dict()) # strongest down / up
# 9. Save the model with its metadata
Path("models").mkdir(exist_ok=True)
meta = {"model_version": "1.0.0", "sklearn_version": sklearn.__version__,
"features": list(X.columns), "test_roc_auc": round(test_auc, 4)}
joblib.dump({"pipeline": best, "metadata": meta}, "models/churn.joblib")
Path("models/churn.json").write_text(json.dumps(meta, indent=2))
print(sorted(meta), np.round(best.predict_proba(X_test.head(2))[:, 1], 3))
Output
baseline CV AUC 0.500
best {'model__C': 1.0} CV AUC 0.813 ± 0.015
{'contract': 0.086, 'tenure_months': 0.074, 'support_tickets': 0.05}
test AUC 0.815
{'cat__contract_two-year': 0.43, 'cat__contract_month-to-month': 2.61}
['features', 'model_version', 'sklearn_version', 'test_roc_auc'] [0.012 0.487]
Trap Symptom Fix
no clear target or decision a model nobody uses step 1: write the decision and the metric first
features not known at prediction time great CV scores, useless in production check each feature’s timestamp against the prediction moment
scaling or encoding before the split optimistic scores (leakage) fit preprocessing inside a Pipeline
a random split for grouped or time data the same customer or the future in train and test GroupKFold, TimeSeriesSplit, a cut-off date
no baseline “0.85 accuracy” when 81% of rows are one class DummyClassifier, seasonal naive
accuracy on imbalanced classes a model that never predicts the rare class looks good ROC-AUC, PR-AUC, recall at a threshold
tuning on the test set the final score is optimistic tune with CV; touch the test set once
a single CV number differences smaller than the noise look real report the spread; compare with the same splitter
threshold chosen on the test set an optimistic precision or recall choose it on validation data or out-of-fold predictions
a target leak one feature with huge importance step 6: permutation importance on validation data, before the test; drop leaks, rerun
going back after the test score the test set has guided a decision; the score is optimistic report it, or set aside a new test set
a model saved without metadata nobody knows which data, versions or threshold bundle + sidecar with versions, features, metrics
no monitoring silent decay after a change upstream PSI per feature, the metric on new labels
retraining by hand a new model that differs for unknown reasons one training script, a config file, tracked runs

This reference pairs Big-O growth classes and amortized rules with the pointer, tree, graph, and probabilistic structures used in engineering and ML systems. Every code block shares one session using data/products.csv and data/houses.csv:

from collections import OrderedDict
import hashlib
import math
import numpy as np
import pandas as pd
from scipy.spatial import KDTree
products = pd.read_csv("data/products.csv")
houses = pd.read_csv("data/houses.csv")
I want to… Use… Complexity
estimate runtime growth for large nn Big-O upper bound on dominant term drop constants and lower-order terms
analyze a structure with rare expensive resizes amortized cost (aggregate or potential method) list.append is O(1)O(1) amortized
O(1) lookup plus O(1) eviction of oldest entry LRU cache (OrderedDict or hash map + doubly linked list) O(1)O(1) get and put
memoize pure function calls in Python @functools.lru_cache(maxsize=256) O(1)O(1) average lookup
prefix search and autocomplete on strings Trie (prefix tree) O(L)O(L) per key of length LL
range queries and ordered iteration balanced BST (AVL / Red-Black) or B-tree O(log⁡n)O(\log n) search, insert, delete
track connected components dynamically Union-Find (DSU) with path compression + rank O(α(n))≈O(1)O(\alpha(n)) \approx O(1) amortized
fast k-NN or radius search in low-D numeric space scipy.spatial.KDTree O(log⁡n)O(\log n) query for d≤20d \le 20
test set membership with tiny fixed memory Bloom filter (bit array + kk hash functions) O(k)O(k) insert/query; no false negatives
find near-duplicate sets or documents at scale MinHash + Locality-Sensitive Hashing (LSH) sublinear candidate lookup
Class Name n=103n = 10^3 ops n=106n = 10^6 ops Typical examples
O(1)O(1) constant 11 11 dict lookup, array index, deque.popleft()
O(α(n))O(\alpha(n)) inverse Ackermann ≤4\le 4 ≤4\le 4 Union-Find with compression and rank
O(log⁡n)O(\log n) logarithmic ≈10\approx 10 ≈20\approx 20 binary search, balanced BST, heap push/pop
O(n)O(n) linear 10310^3 10610^6 single scan, two pointers, Quickselect average, heapify
O(nlog⁡n)O(n \log n) linearithmic 10410^4 2×1072 \times 10^7 Timsort (sorted), mergesort, building KD-tree
O(n2)O(n^2) quadratic 10610^6 101210^{12} nested loops, pairwise distances, 2D DP on n×nn \times n
O(n3)O(n^3) cubic 10910^9 101810^{18} dense matrix multiply (n×nn \times n), Floyd–Warshall
O(2n)O(2^n) exponential intractable intractable brute-force subsets, unmemoized Fibonacci
O(n!)O(n!) factorial intractable intractable brute-force permutations (TSP)

For divide-and-conquer recurrences T(n)=aT(n/b)+O(nd)T(n) = a T(n / b) + O(n^d) (Master Theorem):

Condition Result Example
d>log⁡bad > \log_b a (work at root dominates) T(n)=O(nd)T(n) = O(n^d) Quickselect average (a=1,b=2,d=1⇒O(n)a=1, b=2, d=1 \Rightarrow O(n))
d=log⁡bad = \log_b a (equal work per level) T(n)=O(ndlog⁡n)T(n) = O(n^d \log n) mergesort (a=2,b=2,d=1⇒O(nlog⁡n)a=2, b=2, d=1 \Rightarrow O(n \log n)), binary search (a=1,b=2,d=0⇒O(log⁡n)a=1, b=2, d=0 \Rightarrow O(\log n))
d<log⁡bad < \log_b a (leaves dominate) T(n)=O(nlog⁡ba)T(n) = O(n^{\log_b a}) Karatsuba (a=3,b=2,d=1⇒O(n1.585)a=3, b=2, d=1 \Rightarrow O(n^{1.585}))
Amortized scenario Worst single op Amortized cost Why
dynamic array (list.append) O(n)O(n) on resize O(1)O(1) doubling capacity copies 1+2+4+⋯+n<2n1 + 2 + 4 + \dots + n < 2n items
hash table (dict / set insert) O(n)O(n) on rehash O(1)O(1) load factor capped (≈2/3\approx 2/3 in CPython); doubling spreads rehash cost
monotonic stack / sliding window O(n)O(n) pops in one step O(1)O(1) per item each element enters and leaves the structure at most once
Union-Find (find + union) O(log⁡n)O(\log n) O(α(n))O(\alpha(n)) path compression flattens trees; rank keeps height bounded
binary heap build (heapq.heapify) — O(n)O(n) total bottom-up sifting does most work on shallow subtrees

Average-case time unless marked; nn is items, LL is string length, kk is hash count, dd is dimension.

Structure Lookup / Query Insert Delete Space Best for
list (dynamic array) O(1)O(1) index, O(n)O(n) scan O(1)O(1) end, O(n)O(n) front O(1)O(1) end, O(n)O(n) front O(n)O(n) sequences, stacks, cache-friendly scans
deque (doubly linked blocks) O(1)O(1) ends, O(n)O(n) mid O(1)O(1) both ends O(1)O(1) both ends O(n)O(n) FIFO queues, BFS, fixed windows
dict / set (hash table) O(1)O(1) avg, O(n)O(n) worst O(1)O(1) avg O(1)O(1) avg O(n)O(n) key lookup, deduplication, counting
heapq (binary min-heap) O(1)O(1) min O(log⁡n)O(\log n) O(log⁡n)O(\log n) min O(n)O(n) priority queues, Dijkstra, top-kk
Doubly linked list O(n)O(n) by value O(1)O(1) given node O(1)O(1) given node O(n)O(n) LRU eviction order, splice
Balanced BST / B-tree O(log⁡n)O(\log n) O(log⁡n)O(\log n) O(log⁡n)O(\log n) O(n)O(n) sorted ranges, SQL indexes (B+ tree)
Trie (prefix tree) O(L)O(L) O(L)O(L) O(L)O(L) O(∑L)O(\sum L) autocomplete, prefix counts, IP routing
Union-Find (DSU) O(α(n))O(\alpha(n)) find O(α(n))O(\alpha(n)) union not supported O(n)O(n) connected components, Kruskal MST
KD-tree (low dd) O(log⁡n)O(\log n) avg, O(n)O(n) high dd O(log⁡n)O(\log n) static build O(nlog⁡n)O(n \log n) rebuild O(n)O(n) spatial / low-D nearest neighbors
Bloom filter O(k)O(k) O(k)O(k) not supported (needs counting filter) O(m)O(m) bits memory-tight duplicate / cache guard

An LRU (Least Recently Used) cache combines a hash map (for O(1)O(1) key lookup) with a doubly linked list (for O(1)O(1) move-to-front and tail eviction). In Python, collections.OrderedDict implements this combination in C; for pure functions, functools.lru_cache wraps it as a decorator.

class LRUCache:
"""Fixed-capacity LRU cache with O(1) get and put."""
def __init__(self, capacity: int) -> None:
self.capacity = capacity
self.store: OrderedDict[str, float] = OrderedDict()
self.hits = 0
self.misses = 0
def get(self, key: str) -> float | None:
if key not in self.store:
self.misses += 1
return None
self.hits += 1
self.store.move_to_end(key)
return self.store[key]
def put(self, key: str, value: float) -> None:
if key in self.store:
self.store.move_to_end(key)
self.store[key] = value
if len(self.store) > self.capacity:
self.store.popitem(last=False)
prices = dict(zip(products["product_id"], products["unit_price"]))
cache = LRUCache(capacity=3)
for pid in ["P001", "P002", "P003", "P001", "P004", "P002"]:
if cache.get(pid) is None:
cache.put(pid, prices[pid])
print("keys (LRU -> MRU):", list(cache.store.keys()))
print(f"hits={cache.hits}, misses={cache.misses}")
Output
keys (LRU -> MRU): ['P001', 'P004', 'P002']
hits=1, misses=5
Tree variant Node branching Key property Primary use
Binary Search Tree (BST) 2 children left < node < right; degrades to O(n)O(n) on sorted input teaching baseline
AVL / Red-Black tree 2 children rotations enforce height O(log⁡n)O(\log n) in-memory sorted maps (std::map)
B-tree / B+ tree hundreds of keys per page wide shallow nodes match disk/cache pages; leaves linked PostgreSQL, SQLite, InnoDB indexes
Trie (prefix tree) one edge per character shared prefixes stored once; lookup depends only on key length LL autocomplete, spell-check prefixes
class TrieNode:
__slots__ = ("children", "end_word")
def __init__(self) -> None:
self.children: dict[str, TrieNode] = {}
self.end_word: str | None = None
class Trie:
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for ch in word.lower():
node = node.children.setdefault(ch, TrieNode())
node.end_word = word
def autocomplete(self, prefix: str) -> list[str]:
node = self.root
for ch in prefix.lower():
if ch not in node.children:
return []
node = node.children[ch]
results: list[str] = []
stack = [node]
while stack:
cur = stack.pop()
if cur.end_word is not None:
results.append(cur.end_word)
stack.extend(cur.children.values())
return sorted(results)
trie = Trie()
for name in products["product"]:
trie.insert(name)
print("prefix 'w':", trie.autocomplete("w"))
print("prefix 'co':", trie.autocomplete("co"))
Output
prefix 'w': ['Waterproof Rain Jacket', 'Weeknight Kitchen Cookbook', 'Wireless Earbuds']
prefix 'co': ['Cotton Bed Sheet Set']

Union-Find maintains a partition of nn elements into disjoint sets. Always combine path compression (pointing visited nodes straight to the root during find) with union by rank (attaching the shorter tree under the taller one) to guarantee O(α(n))O(\alpha(n)) amortized time per operation.

class UnionFind:
def __init__(self, n: int) -> None:
self.parent = list(range(n))
self.rank = [0] * n
self.components = n
def find(self, x: int) -> int:
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path halving
x = self.parent[x]
return x
def union(self, a: int, b: int) -> bool:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
self.components -= 1
return True
uf = UnionFind(6)
for u, v in [(0, 1), (1, 2), (3, 4), (0, 2)]:
uf.union(u, v)
print("components:", uf.components)
print("connected(0, 2):", uf.find(0) == uf.find(2))
print("connected(0, 4):", uf.find(0) == uf.find(4))
Output
components: 3
connected(0, 2): True
connected(0, 4): False

KD-trees for low-dimensional nearest neighbors

Section titled “KD-trees for low-dimensional nearest neighbors”

A KD-tree splits dd-dimensional points along alternating coordinate medians. Always standardize features before building the tree so Euclidean distance is not dominated by one high-magnitude column. Above d≈20d \approx 20, most branches overlap the query sphere (“curse of dimensionality”) and approximate methods (HNSW, IVF) beat KD-trees.

cols = ["sqft", "bedrooms", "bathrooms", "distance_to_center_km"]
raw = houses[cols].to_numpy(dtype=float)
X = (raw - raw.mean(axis=0)) / raw.std(axis=0)
tree = KDTree(X)
dists, idx = tree.query(X[0], k=4)
# Verify distances against brute-force Euclidean search
brute_dists = np.sort(np.linalg.norm(X - X[0], axis=1))[:4]
print("nearest ids:", houses.iloc[idx]["house_id"].tolist())
print("distances match brute force:", np.allclose(dists, brute_dists))
print("within radius 0.25:", len(tree.query_ball_point(X[0], r=0.25)))
Output
nearest ids: ['H0001', 'H2759', 'H2384', 'H2075']
distances match brute force: True
within radius 0.25: 20

A Bloom filter maps each item through kk hash functions into an mm-bit array. If any bit is 0, the item is definitely absent (0% false negatives). If all kk bits are 1, it is probably present with approximate false-positive rate:

p≈(1−e−kn/m)k,kopt=mnln⁡2,m≈−nln⁡p(ln⁡2)2p \approx \left(1 - e^{-kn / m}\right)^k, \qquad k_{\text{opt}} = \frac{m}{n} \ln 2, \qquad m \approx -\frac{n \ln p}{(\ln 2)^2}
Structure Problem solved Exact or approximate Memory driver
Bloom filter fast membership / duplicate guard no false negatives, tunable false positives ~10 bits per item for 1% FP
HyperLogLog distinct count (COUNT DISTINCT) ~1–2% relative error a few KB for billions of items
Count-Min Sketch heavy-hitter frequency estimates overestimates only, never underestimates O(1εln⁡1δ)O(\frac{1}{\varepsilon}\ln\frac{1}{\delta}) counters
MinHash + LSH near-duplicate sets (Jaccard similarity) candidate pairs above threshold ss bb bands ×\times rr rows; P(match)=1−(1−sr)bP(\text{match}) = 1 - (1 - s^r)^b
class BloomFilter:
"""Bit-array Bloom filter using double hashing over SHA-256."""
def __init__(self, n_items: int, fp_rate: float = 0.01) -> None:
self.m = max(8, int(-n_items * math.log(fp_rate) / (math.log(2) ** 2)))
self.k = max(1, round((self.m / n_items) * math.log(2)))
self.bits = bytearray((self.m + 7) // 8)
def _positions(self, item: str) -> list[int]:
digest = hashlib.sha256(item.encode("utf-8")).digest()
h1 = int.from_bytes(digest[:8], "big")
h2 = int.from_bytes(digest[8:16], "big") or 1
return [(h1 + i * h2) % self.m for i in range(self.k)]
def add(self, item: str) -> None:
for pos in self._positions(item):
self.bits[pos >> 3] |= 1 << (pos & 7)
def __contains__(self, item: str) -> bool:
return all((self.bits[p >> 3] >> (p & 7)) & 1 for p in self._positions(item))
bf = BloomFilter(n_items=200, fp_rate=0.01)
for pid in products["product_id"]:
bf.add(pid)
false_pos = sum(f"X{i:03d}" in bf for i in range(200))
print(f"m={bf.m} bits ({len(bf.bits)} bytes), k={bf.k}")
print(f"all inserted found: {all(pid in bf for pid in products['product_id'])}")
print(f"false positives in 200 unseen keys: {false_pos}")
Output
m=1917 bits (240 bytes), k=7
all inserted found: True
false positives in 200 unseen keys: 0
Trap Symptom Fix
measuring list.append on one resize looks O(n)O(n) instead of O(1)O(1) benchmark across nn inserts; amortized cost is O(1)O(1)
list.pop(0) or insert(0, x) in a loop quadratic slowdown on long lists use collections.deque with popleft() / appendleft()
LRU cache with dict + linear scan for oldest O(n)O(n) eviction defeats caching use OrderedDict.move_to_end + popitem(last=False) or @lru_cache
unnormalized case in a Trie "Wireless" and "wireless" split into separate branches normalize with .lower() on both insert and query
Union-Find without path compression or rank chain of depth nn, turning O(α(n))O(\alpha(n)) into O(n)O(n) use both path compression (or halving) and union by rank/size
building a KDTree on raw unscaled features sqft (thousands) swamps bathrooms (1–5) in distance standardize columns before KDTree(X)
using a KDTree on 100-D embeddings slower than brute force use brute-force matrix multiply for small nn or HNSW/FAISS for large nn
deleting from a standard Bloom filter clearing a bit causes false negatives for other keys use a counting Bloom filter or rebuild periodically
using Python’s built-in hash() in a persisted Bloom filter PYTHONHASHSEED randomizes hashes across processes use deterministic hashing (hashlib.sha256 or blake2b)

Most algorithmic problems reduce to a small set of reusable patterns. Use the recognition table to map problem cues to the right template, then adapt the minimal Python skeleton. All runnable blocks share one session using data/houses.csv and data/reviews.csv:

from collections import defaultdict, deque
import heapq
import numpy as np
import pandas as pd
houses = pd.read_csv("data/houses.csv")
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)
I want to… Use… Time
find a pair or remove duplicates in a sorted array two pointers (opposite or fast/slow) O(n)O(n)
find the best contiguous subarray or substring sliding window (expand right, shrink left) O(n)O(n)
find the minimum feasible threshold or capacity binary search on the answer space O(nlog⁡R)O(n \log R)
maintain a running top-kk or merge kk sorted streams min-heap (heapq) O(nlog⁡k)O(n \log k)
shortest path in an unweighted graph or grid BFS (deque) O(V+E)O(V + E)
explore all paths, connected components, or cycle checks DFS (recursive or explicit stack) O(V+E)O(V + E)
shortest path with non-negative edge weights Dijkstra (heapq + lazy stale-entry skip) O((V+E)log⁡V)O((V + E)\log V)
shortest path with negative weights / negative cycles Bellman–Ford (relax edges V−1V - 1 times) O(VE)O(VE)
order tasks with dependencies and detect cycles Kahn’s topological sort (deque + in-degrees) O(V+E)O(V + E)
optimize over overlapping subproblems DP (top-down @lru_cache or bottom-up table) O(states×transitions)O(\text{states} \times \text{transitions})
schedule maximum non-overlapping intervals greedy sort by end time O(nlog⁡n)O(n \log n)
find the kk-th smallest item or median without sorting Quickselect (randomized partition) O(n)O(n) expected
If you see… Pattern Key invariant / trick Complexity
sorted array + target sum / deduplicate in place Two pointers move left or right monotonically O(n)O(n) time, O(1)O(1) space
“longest/shortest contiguous subarray/substring with…” Sliding window expand right; while invalid, shrink left O(n)O(n) time
“next greater/smaller element” or span of bars Monotonic stack pop elements that violate sorted order O(n)O(n) amortized
“minimum capacity / speed so condition holds” (monotonic predicate) Binary search on answer lo infeasible, hi feasible; mid = (lo + hi) // 2 O(nlog⁡R)O(n \log R)
“top kk”, “streaming median”, or “merge kk sorted lists” Heap (heapq) keep size-kk min-heap (or max-heap + min-heap for median) O(nlog⁡k)O(n \log k)
“minimum steps / hops” in unweighted graph or grid BFS mark visited when enqueuing, not when popping O(V+E)O(V + E)
“all subsets / combinations / permutations” Backtracking (DFS) choose → recurse → undo choice O(2n)O(2^n) or O(n!)O(n!)
“shortest path” with weights ≥0\ge 0 Dijkstra skip popped (d, u) if d > dist[u] O((V+E)log⁡V)O((V + E)\log V)
“prerequisites”, “build order”, “pipeline DAG” Kahn’s topo sort push nodes with in_degree == 0; cycle if len(order) < V O(V+E)O(V + E)
“count ways”, “min cost”, “can reach”, choice at step ii 1D DP dp[i] depends on earlier states; compress to O(1)O(1) if rolling O(n)O(n)–O(n2)O(n^2)
two sequences (align, edit distance, LCS) or item + budget 2D DP table dp[i][j]; can often keep only previous row O(nm)O(nm)
“maximum non-overlapping intervals” or “minimum coins (canonical)” Greedy prove exchange property; sort by end time for intervals O(nlog⁡n)O(n \log n)
“kk-th smallest / percentile” in unsorted array Quickselect random pivot avoids O(n2)O(n^2) on sorted input O(n)O(n) avg

Sliding window and binary search on answer

Section titled “Sliding window and binary search on answer”

Use sliding window when adding an element at right and removing at left moves a condition monotonically (non-negative numbers, character counts). Use binary search on answer whenever a check feasible(x) flips once from False to True.

def longest_subarray_under_budget(costs: list[int], budget: int) -> int:
"""Length of the longest contiguous slice with sum <= budget."""
left = total = best = 0
for right, val in enumerate(costs):
total += val
while total > budget:
total -= costs[left]
left += 1
best = max(best, right - left + 1)
return best
def min_truck_capacity(weights: list[int], days: int) -> int:
"""Smallest daily truck capacity to ship weights in order within `days`."""
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = (lo + hi) // 2
used, load = 1, 0
for w in weights:
if load + w > mid:
used += 1
load = 0
load += w
if used <= days:
hi = mid
else:
lo = mid + 1
return lo
print("longest window:", longest_subarray_under_budget([4, 2, 1, 5, 1, 2], budget=8))
print("min capacity:", min_truck_capacity([3, 2, 2, 4, 1, 4], days=3))
Output
longest window: 3
min capacity: 6
Algorithm Edge weights Finds Data structure Time
BFS unweighted (all 1) shortest path from source deque O(V+E)O(V + E)
DFS any reachability, components, cycles, topo order recursion / list stack O(V+E)O(V + E)
Dijkstra non-negative (≥0\ge 0) single-source shortest paths heapq min-heap O((V+E)log⁡V)O((V + E)\log V)
Bellman–Ford any (detects negative cycles) single-source shortest paths edge list O(VE)O(VE)
A* non-negative + admissible heuristic hh shortest path to one goal heapq keyed by g+hg + h depends on hh
Kahn’s algorithm directed graph topological order + cycle check deque + in_degree O(V+E)O(V + E)

Dijkstra with path reconstruction and Kahn’s topological sort

Section titled “Dijkstra with path reconstruction and Kahn’s topological sort”
def dijkstra(
graph: dict[str, list[tuple[str, float]]], start: str, goal: str
) -> tuple[float, list[str]]:
dist: dict[str, float] = {start: 0.0}
prev: dict[str, str | None] = {start: None}
heap: list[tuple[float, str]] = [(0.0, start)]
while heap:
d, u = heapq.heappop(heap)
if d > dist.get(u, float("inf")):
continue
if u == goal:
break
for v, w in graph.get(u, []):
nd = d + w
if nd < dist.get(v, float("inf")):
dist[v] = nd
prev[v] = u
heapq.heappush(heap, (nd, v))
path: list[str] = []
cur: str | None = goal
while cur is not None:
path.append(cur)
cur = prev.get(cur)
return dist[goal], path[::-1]
routes = {
"Chicago": [("Detroit", 283), ("Atlanta", 716), ("Denver", 1003)],
"Detroit": [("New York", 614), ("Atlanta", 722)],
"Atlanta": [("New York", 865), ("Houston", 793)],
"Denver": [("Houston", 1031)],
"New York": [],
"Houston": [],
}
miles, best_path = dijkstra(routes, "Chicago", "New York")
print(f"shortest route: {best_path} ({miles:.0f} mi)")
def topo_sort(nodes: list[str], edges: list[tuple[str, str]]) -> list[str]:
"""Return topological order or raise ValueError if a cycle exists."""
adj: dict[str, list[str]] = defaultdict(list)
indeg = {n: 0 for n in nodes}
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
q = deque(n for n in nodes if indeg[n] == 0)
order: list[str] = []
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
if len(order) != len(nodes):
raise ValueError("Cycle detected in dependency graph")
return order
steps = ["ingest", "validate", "clean", "features", "train", "export"]
deps = [
("ingest", "validate"),
("validate", "clean"),
("clean", "features"),
("features", "train"),
("train", "export"),
]
print("pipeline order:", topo_sort(steps, deps))
Output
shortest route: ['Chicago', 'Detroit', 'New York'] (897 mi)
pipeline order: ['ingest', 'validate', 'clean', 'features', 'train', 'export']

Every DP solution defines four pieces before writing code:

  1. State: what dp[i] or dp[i][j] means in plain words.
  2. Transition: how dp[i] is built from strictly smaller states.
  3. Base cases: empty prefix, zero budget, or single element.
  4. Evaluation order: top-down (@lru_cache) follows recursion naturally; bottom-up fills a table iteratively with lower overhead and easy row compression.
Style Pros Cons When to pick
Top-down (@lru_cache) writes directly from recurrence; computes only reachable states recursion limit (~1000 in Python); dict lookup overhead trees, sparse state spaces, quick prototypes
Bottom-up (tabulation) no recursion limit; easy to drop memory from O(nm)O(nm) to O(m)O(m) must order loops carefully 1D/2D grids, edit distance, knapsack, production loops

Levenshtein edit distance and 0/1 knapsack

Section titled “Levenshtein edit distance and 0/1 knapsack”
def edit_distance(a: str, b: str) -> int:
"""Minimum single-character inserts, deletes, or substitutions."""
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, start=1):
curr = [i] + [0] * len(b)
for j, cb in enumerate(b, start=1):
cost = 0 if ca == cb else 1
curr[j] = min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost)
prev = curr
return prev[-1]
def knapsack_01(weights: list[int], values: list[int], capacity: int) -> int:
"""Maximum value fitting in `capacity`, using each item at most once."""
dp = [0] * (capacity + 1)
for w, v in zip(weights, values):
for c in range(capacity, w - 1, -1): # iterate backward to prevent reuse
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
vocab = ["received", "definitely", "quality", "battery", "recommend"]
typos = ["recieved", "definately", "qualty", "batery"]
fixes = [f"{t}->{min(vocab, key=lambda w: edit_distance(t, w))}" for t in typos]
print("typo fixes:", ", ".join(fixes))
typo_hits = reviews["text"].str.contains("|".join(typos), case=False).sum()
print("reviews with those typos:", int(typo_hits))
print("knapsack best value:", knapsack_01([2, 3, 4, 5], [3, 4, 5, 8], capacity=7))
Output
typo fixes: recieved->received, definately->definitely, qualty->quality, batery->battery
reviews with those typos: 73
knapsack best value: 11

Greedy works only when a locally optimal choice never blocks a globally optimal solution (the greedy-choice property). For non-overlapping intervals, sorting by finish time leaves the maximum room for remaining intervals; sorting by start time or shortest duration fails.

Quickselect finds the kk-th smallest element in O(n)O(n) expected time by partitioning around a random pivot and recursing on only one side.

def max_non_overlapping(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
"""Select the largest set of non-overlapping [start, end] intervals."""
chosen: list[tuple[int, int]] = []
last_end = -1
for start, end in sorted(intervals, key=lambda iv: iv[1]):
if start >= last_end:
chosen.append((start, end))
last_end = end
return chosen
def quickselect(arr: list[int], k: int, rng: np.random.Generator) -> int:
"""Return the k-th smallest item (0-indexed) in O(n) expected time."""
nums = arr.copy()
lo, hi = 0, len(nums) - 1
while lo <= hi:
pivot = nums[int(rng.integers(lo, hi + 1))]
lt, i, gt = lo, lo, hi # 3-way partition handles duplicate values cleanly
while i <= gt:
if nums[i] < pivot:
nums[lt], nums[i] = nums[i], nums[lt]
lt += 1
i += 1
elif nums[i] > pivot:
nums[i], nums[gt] = nums[gt], nums[i]
gt -= 1
else:
i += 1
if k < lt:
hi = lt - 1
elif k > gt:
lo = gt + 1
else:
return nums[k]
raise RuntimeError("unreachable")
campaigns = [(1, 6), (2, 4), (4, 7), (5, 9), (7, 10)]
print("greedy schedule:", max_non_overlapping(campaigns))
prices = houses["price"].tolist()
rng = np.random.default_rng(42)
k_med = len(prices) // 2
qs_val = quickselect(prices, k_med, rng)
exact_val = sorted(prices)[k_med]
print(f"Quickselect price[{k_med}]: {qs_val} (matches sorted: {qs_val == exact_val})")
Output
greedy schedule: [(2, 4), (4, 7), (7, 10)]
Quickselect price[1500]: 376000 (matches sorted: True)
Trap Symptom Fix
sliding window with negative numbers shrinking left can increase the sum, missing the optimal window use prefix sums + hash map or monotonic deque
marking BFS nodes visited on pop instead of enqueue duplicate nodes flood the queue (exponential blow-up on grids) add to visited immediately when appending to deque
running Dijkstra on negative edge weights returns a suboptimal path without error use Bellman–Ford when any edge weight can be negative
forgetting if d > dist[u]: continue in Dijkstra stale heap entries re-relax all neighbors skip outdated entries popped from heapq
forward loop for c in range(w, cap + 1) in 1D 0/1 knapsack silently reuses the same item multiple times (unbounded knapsack) iterate c backward from capacity down to w
picking a greedy sort key without a counterexample check sorting intervals by start time or length fails on overlapping spans sort by earliest end time for interval scheduling
2-way Quickselect on arrays with many duplicates degrades toward O(n2)O(n^2) use 3-way (Dutch National Flag) partition + random pivot
deep top-down DP recursion on n>1000n > 1000 RecursionError: maximum recursion depth exceeded rewrite bottom-up iteratively
binary search while lo <= hi with hi = mid infinite loop when lo == hi use while lo < hi with mid = (lo + hi) // 2 and lo = mid + 1 / hi = mid

Linear algebra is the working language of numerical Python, least squares, PCA, embeddings, and neural networks. This sheet covers notation, matrix identities, decompositions, and the np.linalg / scipy.linalg API. All runnable blocks share one session using data/houses.csv, data/customers.csv, and data/sales.csv:

import numpy as np
import pandas as pd
from scipy import linalg
houses = pd.read_csv("data/houses.csv")
customers = pd.read_csv("data/customers.csv")
sales = pd.read_csv("data/sales.csv")
I want to… Use… Notes
multiply matrices or matrix-vector A @ B, A @ x never * (that is elementwise)
compute dot product or cosine similarity u @ v, (u @ v) / (norm(u) * norm(v)) np.linalg.norm
vector L1L_1, L2L_2, L∞L_\infty norms np.linalg.norm(v, ord=1 / 2 / np.inf) default is L2L_2
matrix Frobenius or spectral norm np.linalg.norm(A, "fro") / ord=2 spectral norm =σmax⁡(A)= \sigma_{\max}(A)
solve a square linear system Ax=bAx = b np.linalg.solve(A, b) faster and cleaner than inv(A) @ b
solve least squares min⁡∥Xw−y∥22\min \Vert Xw - y \Vert_2^2 np.linalg.lstsq(X, y, rcond=None) SVD-based; handles rank deficiency
check linear independence / collinearity np.linalg.matrix_rank(X), np.linalg.cond(X) κ>104\kappa > 10^4 signals ill-conditioning
orthonormal basis for column space Q, R = np.linalg.qr(X, mode="reduced") Q⊤Q=IQ^\top Q = I; stable OLS
eigenvalues of a symmetric matrix vals, vecs = np.linalg.eigh(S) real, sorted ascending, orthonormal vecs
test symmetric positive definiteness np.linalg.cholesky(S) succeeds iff all λi>0\lambda_i > 0
full or reduced SVD A=UΣV⊤A = U \Sigma V^\top U, s, Vt = np.linalg.svd(A, full_matrices=False) Vt is already transposed (V⊤V^\top)
Moore–Penrose pseudoinverse A+A^+ np.linalg.pinv(A) replaces nonzero σi\sigma_i with 1/σi1/\sigma_i
best rank-kk matrix approximation (U[:, :k] * s[:k]) @ Vt[:k, :] Eckart–Young optimal in Frobenius & spectral norm
Operation Math Shapes NumPy
inner (dot) product u⊤v=∑iuiviu^\top v = \sum_i u_i v_i (n,),(n,)→scalar(n,), (n,) \to \text{scalar} u @ v or np.dot(u, v)
outer product uv⊤u v^\top (m,),(n,)→(m,n)(m,), (n,) \to (m, n) np.outer(u, v)
matrix multiply (AB)ij=∑kAikBkj(AB)_{ij} = \sum_k A_{ik} B_{kj} (m,k)×(k,n)→(m,n)(m, k) \times (k, n) \to (m, n) A @ B
Hadamard (elementwise) (A⊙B)ij=AijBij(A \odot B)_{ij} = A_{ij} B_{ij} (m,n)×(m,n)→(m,n)(m, n) \times (m, n) \to (m, n) A * B
transpose (A⊤)ij=Aji(A^\top)_{ij} = A_{ji} (m,n)→(n,m)(m, n) \to (n, m) A.T
trace tr(A)=∑iAii=∑iλi\mathrm{tr}(A) = \sum_i A_{ii} = \sum_i \lambda_i (n,n)→scalar(n, n) \to \text{scalar} np.trace(A)
determinant det⁡(A)=∏iλi\det(A) = \prod_i \lambda_i (volume scale) (n,n)→scalar(n, n) \to \text{scalar} np.linalg.det(A)
vector LpL_p norm ∥v∥p=(∑i∣vi∣p)1/p\Vert v \Vert_p = (\sum_i \vert v_i \vert^p)^{1/p} (n,)→R≥0(n,) \to \mathbb{R}_{\ge 0} np.linalg.norm(v, ord=p)
Frobenius norm ∥A∥F=∑i,jAij2=∑iσi2\Vert A \Vert_F = \sqrt{\sum_{i,j} A_{ij}^2} = \sqrt{\sum_i \sigma_i^2} (m,n)→R≥0(m, n) \to \mathbb{R}_{\ge 0} np.linalg.norm(A, "fro")
spectral norm ∥A∥2=max⁡∥x∥2=1∥Ax∥2=σmax⁡\Vert A \Vert_2 = \max_{\Vert x \Vert_2 = 1} \Vert Ax \Vert_2 = \sigma_{\max} (m,n)→R≥0(m, n) \to \mathbb{R}_{\ge 0} np.linalg.norm(A, ord=2)

Key algebraic identities: (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top, (AB)−1=B−1A−1(AB)^{-1} = B^{-1} A^{-1}, tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA), det⁡(AB)=det⁡(A)det⁡(B)\det(AB) = \det(A)\det(B), and det⁡(A⊤)=det⁡(A)\det(A^\top) = \det(A).

u = np.array([3.0, -4.0, 0.0])
v = np.array([1.0, 2.0, 2.0])
cos_sim = (u @ v) / (np.linalg.norm(u) * np.linalg.norm(v))
print("L1, L2, Linf:", [float(np.linalg.norm(u, p)) for p in (1, 2, np.inf)])
print("cosine similarity:", round(float(cos_sim), 4))
Output
L1, L2, Linf: [7.0, 5.0, 4.0]
cosine similarity: -0.3333

Rank, span, conditioning and linear systems

Section titled “Rank, span, conditioning and linear systems”

For an m×nm \times n matrix AA:

  • Rank r=rank(A)≤min⁡(m,n)r = \mathrm{rank}(A) \le \min(m, n) is the number of linearly independent columns (and rows), equal to the number of nonzero singular values.
  • Rank–Nullity Theorem: rank(A)+dim⁡(ker⁡A)=n\mathrm{rank}(A) + \dim(\ker A) = n.
  • Condition number: κ2(A)=σmax⁡(A)/σmin⁡(A)≥1\kappa_2(A) = \sigma_{\max}(A) / \sigma_{\min}(A) \ge 1. Each order of magnitude in κ\kappa can cost roughly one decimal digit of accuracy when solving Ax=bAx = b. Notice that forming normal equations X⊤XX^\top X squares the condition number: κ(X⊤X)=κ(X)2\kappa(X^\top X) = \kappa(X)^2.
sub = customers[["monthly_charges", "tenure_months", "total_charges"]].dropna()
raw = sub.to_numpy()
std = (raw - raw.mean(axis=0)) / raw.std(axis=0)
# Add an exact linear combination to show rank drop
rank_def = np.column_stack([std, std[:, 0] + 2 * std[:, 1]])
print(
"raw cond vs standardized cond:",
round(np.linalg.cond(raw), 1),
round(np.linalg.cond(std), 2),
)
print("rank of 3 features:", int(np.linalg.matrix_rank(std)))
print("rank with exact combo:", int(np.linalg.matrix_rank(rank_def)))
Output
raw cond vs standardized cond: 181.8 5.93
rank of 3 features: 3
rank with exact combo: 3

A vector bb projected onto the column space of a full-rank matrix XX is y^=Xw^=Pb\hat{y} = X \hat{w} = P b where the orthogonal projection matrix is P=X(X⊤X)−1X⊤P = X (X^\top X)^{-1} X^\top. Its defining property is that the residual r=b−y^r = b - \hat{y} is perpendicular to every column of XX:

X⊤(y−Xw^)=0  ⟹  X⊤Xw^=X⊤yX^\top (y - X\hat{w}) = 0 \implies X^\top X \hat{w} = X^\top y

Factoring X=QRX = Q R (with Q⊤Q=IQ^\top Q = I and RR upper triangular) avoids squaring the condition number: Rw^=Q⊤yR \hat{w} = Q^\top y is solved directly by back-substitution, and P=QQ⊤P = Q Q^\top.

feat = houses[["sqft", "bedrooms", "bathrooms", "condition"]].to_numpy(dtype=float)
X = np.column_stack([np.ones(len(feat)), (feat - feat.mean(0)) / feat.std(0)])
y = np.log(houses["price"].to_numpy(dtype=float))
# Compare QR, SVD lstsq, and normal equations
Q, R = np.linalg.qr(X, mode="reduced")
w_qr = linalg.solve_triangular(R, Q.T @ y)
w_lstsq, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
w_norm = np.linalg.solve(X.T @ X, X.T @ y)
resid = y - X @ w_qr
print("QR weights:", np.round(w_qr, 4))
print("max diff QR vs lstsq:", f"{np.max(np.abs(w_qr - w_lstsq)):.2e}")
print("max diff QR vs normal eq:", f"{np.max(np.abs(w_qr - w_norm)):.2e}")
print("max |X.T @ resid|:", f"{np.max(np.abs(X.T @ resid)):.2e}")
Output
QR weights: [12.9195 0.3468 -0.0195 0.0508 0.1079]
max diff QR vs lstsq: 1.24e-14
max diff QR vs normal eq: 1.24e-14
max |X.T @ resid|: 3.51e-11

Eigenvalues, symmetric matrices and positive definiteness

Section titled “Eigenvalues, symmetric matrices and positive definiteness”

An eigenvector v≠0v \ne 0 satisfies Av=λvA v = \lambda v: the transformation AA only stretches vv by λ\lambda.

  • Spectral Theorem: Every real symmetric matrix S=S⊤S = S^\top has real eigenvalues and an orthonormal eigenbasis: S=QΛQ⊤S = Q \Lambda Q^\top with Q⊤Q=IQ^\top Q = I.
  • Positive definiteness (SPD): SS is positive definite (S≻0S \succ 0) iff x⊤Sx>0x^\top S x > 0 for all x≠0x \ne 0, iff all λi>0\lambda_i > 0, iff a unique Cholesky factor S=LL⊤S = L L^\top exists. Covariance and correlation matrices are always positive semi-definite (λi≥0\lambda_i \ge 0).
Z = (feat - feat.mean(0)) / feat.std(0)
corr = (Z.T @ Z) / len(Z) # 4x4 feature correlation matrix
vals, vecs = np.linalg.eigh(corr) # ascending order for symmetric matrices
vals, vecs = vals[::-1], vecs[:, ::-1] # sort descending (PCA order)
L = np.linalg.cholesky(corr) # succeeds iff strictly positive definite
print("eigenvalues:", np.round(vals, 4))
print("variance share:", np.round(vals / vals.sum(), 4))
print("reconstructed corr matches:", np.allclose(vecs @ np.diag(vals) @ vecs.T, corr))
print("Cholesky L @ L.T matches:", np.allclose(L @ L.T, corr))
Output
eigenvalues: [2.7378 0.9908 0.1678 0.1035]
variance share: [0.6844 0.2477 0.042 0.0259]
reconstructed corr matches: True
Cholesky L @ L.T matches: True

Every m×nm \times n matrix AA (square or rectangular, full-rank or singular) factors into:

A=UΣV⊤=∑i=1rσiuivi⊤,σ1≥σ2≥⋯≥σr>0A = U \Sigma V^\top = \sum_{i=1}^{r} \sigma_i u_i v_i^\top, \qquad \sigma_1 \ge \sigma_2 \ge \dots \ge \sigma_r > 0
  • Columns of UU (left singular vectors) are orthonormal eigenvectors of AA⊤A A^\top; columns of VV (right singular vectors) are orthonormal eigenvectors of A⊤AA^\top A; σi=λi(A⊤A)\sigma_i = \sqrt{\lambda_i(A^\top A)}.
  • Eckart–Young Theorem: Keeping only the top kk terms Ak=UkΣkVk⊤A_k = U_k \Sigma_k V_k^\top gives the closest rank-kk matrix in Frobenius and spectral norm, with error ∥A−Ak∥F=∑i>kσi2\Vert A - A_k \Vert_F = \sqrt{\sum_{i > k} \sigma_i^2}.
  • Ridge regression via SVD: For X=UΣV⊤X = U \Sigma V^\top, the Ridge solution (X⊤X+λI)−1X⊤y(X^\top X + \lambda I)^{-1} X^\top y shrinks each singular direction by σiσi2+λ\frac{\sigma_i}{\sigma_i^2 + \lambda}:
w^ridge=Vdiag⁡ ⁣(σiσi2+λ)U⊤y\hat{w}_{\text{ridge}} = V \operatorname{diag}\!\left(\frac{\sigma_i}{\sigma_i^2 + \lambda}\right) U^\top y
sales["month"] = sales["order_date"].str.slice(0, 7)
mat = (
sales.pivot_table(
index="store_id", columns="month", values="revenue", aggfunc="sum"
)
.fillna(0.0)
.to_numpy()
)
U, s, Vt = np.linalg.svd(mat, full_matrices=False)
energy = np.cumsum(s**2) / np.sum(s**2)
rank2 = (U[:, :2] * s[:2]) @ Vt[:2, :]
rel_err = np.linalg.norm(mat - rank2, "fro") / np.linalg.norm(mat, "fro")
print("matrix shape:", mat.shape)
print("top 4 singular values:", np.round(s[:4], 1))
print("cumulative energy (k=1..3):", np.round(energy[:3], 4))
print("rank-2 relative Frobenius error:", round(float(rel_err), 4))
Output
matrix shape: (12, 24)
top 4 singular values: [235247.3 25609.5 21027.7 18594.6]
cumulative energy (k=1..3): [0.954 0.9653 0.9729]
rank-2 relative Frobenius error: 0.1863
Function Input requirement Returns When to use
np.linalg.solve(A, b) square, nonsingular xx exact linear system; never inv(A) @ b
np.linalg.lstsq(X, y, rcond=None) any (m,n)(m, n) x, residuals, rank, s least squares, over/underdetermined
np.linalg.qr(X, mode="reduced") any (m,n)(m, n) Q, R orthonormal basis, stable regression
np.linalg.eigh(S) symmetric / Hermitian ascending vals, vecs covariance, correlation, graph Laplacian
np.linalg.eig(A) any square vals, vecs (may be complex) Markov chains, non-symmetric operators
np.linalg.svd(A, full_matrices=False) any (m,n)(m, n) U, s, Vt PCA, low-rank approximation, diagnostics
np.linalg.cholesky(S) symmetric positive definite lower triangular L SPD check, fast SPD solve (cho_solve), MVN sampling
np.linalg.pinv(A) any (m,n)(m, n) A+A^+ minimum-norm least-squares inverse
scipy.linalg.solve_triangular(R, b) triangular R xx back-substitution after QR or Cholesky
scipy.sparse.linalg.svds(A, k) large sparse matrix top-kk singular triplets TF-IDF / user-item matrices (LSA)
Trap Symptom Fix
using A * B for matrix multiplication silent elementwise product or broadcast error use A @ B
solving Ax=bAx = b with np.linalg.inv(A) @ b slower and loses numerical accuracy use np.linalg.solve(A, b)
solving OLS via (X.T @ X) on unscaled features squares condition number κ(X)2\kappa(X)^2; wild weights standardize and use np.linalg.lstsq or QR
forgetting svd returns Vt (V⊤V^\top), not V transposed loadings when projecting X @ V project with X @ Vt.T (or U * s)
calling np.linalg.eig on a symmetric covariance matrix tiny imaginary parts (+0j) and unsorted eigenvalues use np.linalg.eigh (real, sorted, faster)
reading eigh eigenvalues assuming descending order first column is the smallest variance direction reverse with vals[::-1], vecs[:, ::-1]
checking det(A) == 0 to test singularity underflows to 0.0 on well-conditioned large matrices use np.linalg.matrix_rank(A) or np.linalg.cond(A)
computing U @ np.diag(s) @ Vt on large matrices wastes memory building a dense diagonal matrix broadcast (U * s) @ Vt
forgetting to center columns before SVD for PCA first singular vector points toward the mean, not max variance subtract column means: Xc = X - X.mean(axis=0)

Training a model means minimizing a loss function with derivatives. This reference gathers scalar and matrix calculus identities, numerical integration, convexity and Lagrange multipliers, scipy.optimize, modern gradient optimizers, and reverse-mode automatic differentiation. All blocks share one session using data/customers.csv and data/ab_test.csv:

import numpy as np
import pandas as pd
from scipy import integrate, optimize, stats
customers = pd.read_csv("data/customers.csv")
ab = pd.read_csv("data/ab_test.csv")
I want to… Use… Notes
verify an analytical gradient numerically centered difference (f(x+h)−f(x−h))/(2h)(f(x+h)-f(x-h))/(2h) O(h2)O(h^2) error; pick h≈10−5h \approx 10^{-5}
approximate a smooth function near aa 2nd-order Taylor f(a)+f′(a)(x−a)+12f′′(a)(x−a)2f(a) + f'(a)(x-a) + \frac{1}{2}f''(a)(x-a)^2 foundation of Newton’s method
check if a critical point (∇f=0\nabla f = 0) is a minimum Hessian HH positive definite (λmin⁡(H)>0\lambda_{\min}(H) > 0) mixed signs ⇒\Rightarrow saddle point
integrate a 1D function or PDF numerically scipy.integrate.quad(f, a, b) returns (value, abs_error)
integrate sampled grid values np.trapezoid(y, x) or scipy.integrate.simpson replaces deprecated np.trapz
estimate a high-D expectation E[g(X)]\mathbb{E}[g(X)] Monte Carlo 1N∑g(Xi)\frac{1}{N}\sum g(X_i) error O(1/N)O(1/\sqrt{N}), independent of dd
minimize a smooth unconstrained function optimize.minimize(f, x0, jac=grad, method="L-BFGS-B") quasi-Newton; fast on moderate dd
minimize with bounds or constraints method="L-BFGS-B" (box) or "SLSQP" (eq/ineq) pass bounds= and constraints=
find a root g(x)=0g(x) = 0 on bracket [a,b][a, b] optimize.brentq(g, a, b) requires g(a)g(a) and g(b)g(b) opposite signs
train large mini-batch neural networks Adam (lr=1e-3, β1=0.9,β2=0.999\beta_1=0.9, \beta_2=0.999) adaptive per-parameter step sizes
Rule / Function Formula Derivative
Power xnx^n nxn−1n x^{n-1}
Exponential / Log eaxe^{ax}, ln⁡(x)\ln(x) aeaxa e^{ax}, 1/x1/x
Product rule u(x)v(x)u(x) v(x) u′v+uv′u' v + u v'
Quotient rule u(x)/v(x)u(x) / v(x) (u′v−uv′)/v2(u' v - u v') / v^2
Chain rule f(g(x))f(g(x)) f′(g(x))⋅g′(x)f'(g(x)) \cdot g'(x)
Sigmoid σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}} σ(z)(1−σ(z))\sigma(z)(1 - \sigma(z))
Hyperbolic tangent tanh⁡(z)\tanh(z) 1−tanh⁡2(z)1 - \tanh^2(z)
Softplus ln⁡(1+ez)\ln(1 + e^z) σ(z)\sigma(z)
ReLU max⁡(0,z)\max(0, z) 11 if z>0z > 0, 00 if z<0z < 0 (subgradient [0,1][0, 1] at 00)
Huber loss (δ\delta) 12r2\frac{1}{2}r^2 if ∣r∣≤δ\vert r \vert \le \delta else δ(∣r∣−12δ)\delta(\vert r \vert - \frac{1}{2}\delta) rr if ∣r∣≤δ\vert r \vert \le \delta else δ sign(r)\delta\,\mathrm{sign}(r)

Taylor series around aa:

f(x)=∑k=0nf(k)(a)k!(x−a)k+O ⁣((x−a)n+1)f(x) = \sum_{k=0}^{n} \frac{f^{(k)}(a)}{k!} (x - a)^k + O\!\left((x - a)^{n+1}\right)

Useful expansions near x=0x = 0: ex≈1+x+x22e^x \approx 1 + x + \frac{x^2}{2}, ln⁡(1+x)≈x−x22\ln(1 + x) \approx x - \frac{x^2}{2}, and σ(x)≈12+x4−x348\sigma(x) \approx \frac{1}{2} + \frac{x}{4} - \frac{x^3}{48}.

def sigmoid(z: np.ndarray | float) -> np.ndarray | float:
return 1.0 / (1.0 + np.exp(-z))
z = 0.4
h = 1e-5
analytic = sigmoid(z) * (1.0 - sigmoid(z))
numeric = (sigmoid(z + h) - sigmoid(z - h)) / (2.0 * h)
taylor3 = 0.5 + z / 4.0 - (z**3) / 48.0
print(f"sigmoid'(0.4) analytic={analytic:.8f}, numeric={numeric:.8f}")
print(f"sigmoid(0.4) exact={sigmoid(z):.6f}, 3rd-order Taylor={taylor3:.6f}")
Output
sigmoid'(0.4) analytic=0.24026075, numeric=0.24026075
sigmoid(0.4) exact=0.598688, 3rd-order Taylor=0.598667

For f:Rd→Rf: \mathbb{R}^d \to \mathbb{R} and g:Rd→Rmg: \mathbb{R}^d \to \mathbb{R}^m:

  • Gradient ∇f(x)∈Rd\nabla f(x) \in \mathbb{R}^d: points in the direction of steepest ascent; directional derivative along unit vector uu is Duf(x)=∇f(x)⊤uD_u f(x) = \nabla f(x)^\top u.
  • Jacobian (Jg)ij=∂gi∂xj∈Rm×d(J_g)_{ij} = \frac{\partial g_i}{\partial x_j} \in \mathbb{R}^{m \times d}: multivariable chain rule is matrix multiplication Jh∘g(x)=Jh(g(x))Jg(x)J_{h \circ g}(x) = J_h(g(x)) J_g(x).
  • Hessian (Hf)ij=∂2f∂xi∂xj∈Rd×d(H_f)_{ij} = \frac{\partial^2 f}{\partial x_i \partial x_j} \in \mathbb{R}^{d \times d}: symmetric for smooth ff. At ∇f(x∗)=0\nabla f(x^*) = 0: all λi>0⇒\lambda_i > 0 \Rightarrow strict local min; all λi<0⇒\lambda_i < 0 \Rightarrow strict local max; mixed signs ⇒\Rightarrow saddle point.
Expression f(w)f(w) Gradient ∇wf\nabla_w f Hessian ∇w2f\nabla_w^2 f
a⊤wa^\top w aa 00
w⊤Aww^\top A w (general AA) (A+A⊤)w(A + A^\top) w A+A⊤A + A^\top
12w⊤Sw\frac{1}{2} w^\top S w (symmetric SS) SwS w SS
12n∥Xw−y∥22\frac{1}{2n}\Vert Xw - y \Vert_2^2 (MSE) 1nX⊤(Xw−y)\frac{1}{n} X^\top (Xw - y) 1nX⊤X\frac{1}{n} X^\top X
12n∥Xw−y∥22+λ2∥w∥22\frac{1}{2n}\Vert Xw - y \Vert_2^2 + \frac{\lambda}{2}\Vert w \Vert_2^2 (Ridge) 1nX⊤(Xw−y)+λw\frac{1}{n} X^\top (Xw - y) + \lambda w 1nX⊤X+λI\frac{1}{n} X^\top X + \lambda I
Binary log-loss −1n∑[yiln⁡pi+(1−yi)ln⁡(1−pi)]-\frac{1}{n}\sum [y_i \ln p_i + (1-y_i)\ln(1-p_i)] 1nX⊤(p−y)\frac{1}{n} X^\top (p - y) 1nX⊤diag(p(1−p))X\frac{1}{n} X^\top \mathrm{diag}(p(1-p)) X
Softmax + cross-entropy (logits Z=XWZ = XW) ∂L∂Z=1n(P−Y)\frac{\partial L}{\partial Z} = \frac{1}{n}(P - Y), ∂L∂W=1nX⊤(P−Y)\frac{\partial L}{\partial W} = \frac{1}{n} X^\top (P - Y) positive semi-definite
cols = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
raw = customers[cols].to_numpy(dtype=float)
X = np.column_stack([np.ones(len(raw)), (raw - raw.mean(0)) / raw.std(0)])
y = customers["churned"].to_numpy(dtype=float)
def log_loss(w: np.ndarray, reg: float = 1e-2) -> float:
z = X @ w
loss = np.mean(np.logaddexp(0.0, z) - y * z)
return float(loss + 0.5 * reg * np.dot(w[1:], w[1:]))
def log_grad(w: np.ndarray, reg: float = 1e-2) -> np.ndarray:
p = sigmoid(X @ w)
g = (X.T @ (p - y)) / len(y)
g[1:] += reg * w[1:]
return g
def log_hess(w: np.ndarray, reg: float = 1e-2) -> np.ndarray:
p = sigmoid(X @ w)
H = (X.T * (p * (1.0 - p))) @ X / len(y)
H[1:, 1:] += reg * np.eye(X.shape[1] - 1)
return H
w0 = np.zeros(X.shape[1])
num_grad = optimize.approx_fprime(w0, log_loss, 1e-6)
eigvals = np.linalg.eigvalsh(log_hess(w0))
err = np.max(np.abs(log_grad(w0) - num_grad))
print("max |analytic - numeric grad|:", f"{err:.2e}")
print("min Hessian eigenvalue at w=0:", round(float(eigvals.min()), 4))
Output
max |analytic - numeric grad|: 1.30e-07
min Hessian eigenvalue at w=0: 0.2084
Method Formula / Call Best for
Fundamental Theorem ∫abf(x) dx=F(b)−F(a)\int_a^b f(x)\,dx = F(b) - F(a) verifying CDF from PDF
Adaptive quadrature integrate.quad(f, a, b) smooth 1D integrals (supports np.inf)
Grid trapezoid rule np.trapezoid(y, x) tabulated curves, ROC AUC
Monte Carlo expectation E[g(X)]≈1N∑i=1Ng(Xi)\mathbb{E}[g(X)] \approx \frac{1}{N} \sum_{i=1}^N g(X_i) high-dimensional expectations and Bayesian posteriors
rev = ab.loc[ab["converted"] == 1, "revenue"].to_numpy()
s, _, scale = stats.lognorm.fit(rev, floc=0)
dist = stats.lognorm(s=s, loc=0, scale=scale)
prob_quad, _ = integrate.quad(dist.pdf, 20.0, 60.0)
prob_cdf = dist.cdf(60.0) - dist.cdf(20.0)
ev_quad, _ = integrate.quad(lambda x: x * dist.pdf(x), 0.0, np.inf)
rng = np.random.default_rng(42)
ev_mc = float(dist.rvs(size=50_000, random_state=rng).mean())
print(f"P(20 <= X <= 60): quad={prob_quad:.5f}, cdf={prob_cdf:.5f}")
print(f"E[revenue]: quad={ev_quad:.2f}, exact={dist.mean():.2f}, MC={ev_mc:.2f}")
Output
P(20 <= X <= 60): quad=0.60726, cdf=0.60726
E[revenue]: quad=42.42, exact=42.42, MC=42.46

A function ff is convex if f(tx+(1−t)y)≤tf(x)+(1−t)f(y)f(tx + (1-t)y) \le t f(x) + (1-t) f(y) for t∈[0,1]t \in [0, 1] (equivalently, Hf(x)⪰0H_f(x) \succeq 0 everywhere). Every local minimum of a convex function is a global minimum; if Hf(x)≻0H_f(x) \succ 0 (strictly convex), the global minimum is unique.

To minimize f(x)f(x) subject to g(x)=0g(x) = 0, form the Lagrangian L(x,λ)=f(x)+λg(x)\mathcal{L}(x, \lambda) = f(x) + \lambda g(x) and solve ∇xL=0, g(x)=0\nabla_x \mathcal{L} = 0, \, g(x) = 0 — meaning ∇f(x∗)\nabla f(x^*) is parallel to ∇g(x∗)\nabla g(x^*) (contours are tangent). For inequality constraints g(x)≤0g(x) \le 0, the KKT conditions add dual feasibility (λ≥0\lambda \ge 0) and complementary slackness (λg(x∗)=0\lambda g(x^*) = 0). In regularization, the L1L_1 diamond ∥w∥1≤t\Vert w \Vert_1 \le t has sharp corners on the axes (driving exact zeros in Lasso), while the L2L_2 sphere ∥w∥22≤t\Vert w \Vert_2^2 \le t shrinks weights smoothly (Ridge).

# Minimize (w0 - 2)^2 + (w1 - 1)^2 subject to w0^2 + w1^2 <= 1 (L2 ball)
res = optimize.minimize(
lambda w: (w[0] - 2.0) ** 2 + (w[1] - 1.0) ** 2,
x0=np.array([0.0, 0.0]),
method="SLSQP",
constraints={"type": "ineq", "fun": lambda w: 1.0 - np.dot(w, w)},
)
norm_opt = round(float(np.linalg.norm(res.x)), 4)
print("constrained optimum:", np.round(res.x, 4), "norm:", norm_opt)
Output
constrained optimum: [0.8944 0.4472] norm: 1.0
Optimizer Update rule Order Strengths / Best for
Gradient Descent (GD) w←w−ηgw \leftarrow w - \eta g 1st simple; slow in ill-conditioned valleys
SGD + Momentum v←βv+gv \leftarrow \beta v + g, w←w−ηvw \leftarrow w - \eta v 1st damps oscillations; strong generalization on vision CNNs
RMSProp s←βs+(1−β)g2s \leftarrow \beta s + (1-\beta) g^2, w←w−ηs+ϵgw \leftarrow w - \frac{\eta}{\sqrt{s}+\epsilon} g 1st scales step size per coordinate
Adam bias-corrected 1st (mm) and 2nd (vv) moments of gg 1st default for deep learning; use AdamW for weight decay
Newton’s method w←w−H−1gw \leftarrow w - H^{-1} g 2nd quadratic convergence; O(d3)O(d^3) Hessian solve limits dd
L-BFGS / L-BFGS-B approximates H−1gH^{-1} g from last mm steps quasi-2nd O(md)O(md) memory; gold standard for smooth batch convex models
# Compare 80 steps of GD, 80 steps of Adam, 5 steps of Newton, and L-BFGS-B
w_gd = np.zeros(X.shape[1])
for _ in range(80):
w_gd -= 0.5 * log_grad(w_gd)
w_adam = np.zeros(X.shape[1])
m = np.zeros_like(w_adam)
v = np.zeros_like(w_adam)
for t in range(1, 81):
g = log_grad(w_adam)
m = 0.9 * m + 0.1 * g
v = 0.999 * v + 0.001 * (g**2)
m_hat, v_hat = m / (1.0 - 0.9**t), v / (1.0 - 0.999**t)
w_adam -= 0.05 * m_hat / (np.sqrt(v_hat) + 1e-8)
w_newt = np.zeros(X.shape[1])
for _ in range(5):
w_newt -= np.linalg.solve(log_hess(w_newt), log_grad(w_newt))
res_lbfgs = optimize.minimize(
log_loss, np.zeros(X.shape[1]), jac=log_grad, method="L-BFGS-B"
)
print(f"GD (80): loss={log_loss(w_gd):.6f}")
print(f"Adam (80): loss={log_loss(w_adam):.6f}")
print(f"Newton (5): loss={log_loss(w_newt):.6f}")
print(f"L-BFGS ({res_lbfgs.nit}): loss={res_lbfgs.fun:.6f}")
Output
GD (80): loss=0.414188
Adam (80): loss=0.413867
Newton (5): loss=0.413856
L-BFGS (8): loss=0.413856
Mode Propagates Cost for f:Rd→Rmf: \mathbb{R}^d \to \mathbb{R}^m Used for
Finite differences perturbed function evaluations O(d)O(d) evals, truncation/roundoff error gradient checking only
Forward-mode AD tangents v˙=∂v/∂xi\dot{v} = \partial v / \partial x_i (dual numbers) O(d)O(d) passes few inputs, many outputs (d≪md \ll m)
Reverse-mode AD (backprop) adjoints vˉ=∂L/∂v\bar{v} = \partial L / \partial v in reverse topo order O(m)O(m) passes (11 pass for scalar loss) neural networks (d≫1,m=1d \gg 1, m = 1)
class Value:
"""Minimal reverse-mode autograd scalar node."""
def __init__(self, data: float, children: tuple["Value", ...] = ()) -> None:
self.data = float(data)
self.grad = 0.0
self._backward = lambda: None
self._prev = set(children)
def __add__(self, other: "Value") -> "Value":
out = Value(self.data + other.data, (self, other))
def _bw() -> None:
self.grad += out.grad
other.grad += out.grad
out._backward = _bw
return out
def __mul__(self, other: "Value") -> "Value":
out = Value(self.data * other.data, (self, other))
def _bw() -> None:
self.grad += other.data * out.grad
other.grad += self.data * out.grad
out._backward = _bw
return out
def backward(self) -> None:
topo: list[Value] = []
seen: set[Value] = set()
def build(node: Value) -> None:
if node not in seen:
seen.add(node)
for ch in node._prev:
build(ch)
topo.append(node)
build(self)
self.grad = 1.0
for node in reversed(topo):
node._backward()
a, b, c = Value(2.0), Value(-3.0), Value(5.0)
loss = (a * b + c) * (a * b + c) # f(a, b, c) = (ab + c)^2
loss.backward()
print(f"loss={loss.data:.1f}, da={a.grad:.1f}, db={b.grad:.1f}, dc={c.grad:.1f}")
Output
loss=1.0, da=6.0, db=-4.0, dc=-2.0
Trap Symptom Fix
choosing finite-difference h=10−12h = 10^{-12} catastrophic cancellation gives noisy gradients use centered difference with h≈10−5h \approx 10^{-5} to 10−610^{-6}
computing np.log(1 + np.exp(z)) for large z RuntimeWarning: overflow and inf loss use np.logaddexp(0.0, z)
forgetting jac=grad in scipy.optimize.minimize slow finite-difference gradients inside the optimizer pass analytical jac= (and hess= for Newton methods)
ignoring res.success from scipy.optimize.minimize silently uses an unconverged vector check assert res.success, res.message
unscaled features in gradient descent zig-zagging along narrow contours; requires tiny η\eta standardize features to mean 0, std 1 before optimizing
applying L2 weight decay to the bias / intercept term shifts predictions toward zero regularize only w[1:], not the intercept w[0]
setting self.grad = ... instead of += in backprop wrong gradient whenever a node is used twice (fan-out) accumulate with += and zero grads before each pass
passing a one-sided step size too big for Newton’s method diverges far from the minimum add backtracking line search or use L-BFGS-B
assuming a zero gradient means a minimum stuck at a saddle point or local maximum check Hessian eigenvalues or perturb

Probability, Bayesian statistics and information theory

Section titled “Probability, Bayesian statistics and information theory”

This sheet covers probability identities, the core distribution families with scipy.stats parameterizations, conjugate Bayesian updating, MLE vs. MAP regularization, Metropolis–Hastings MCMC, and information-theoretic metrics for ML and drift detection. All blocks share one session using data/sales.csv, data/ab_test.csv, data/houses.csv, data/sensors.csv, and data/customers.csv:

import numpy as np
import pandas as pd
from scipy import stats
from scipy.spatial.distance import jensenshannon
from scipy.special import rel_entr
from sklearn.feature_selection import mutual_info_classif
from sklearn.linear_model import Ridge
sales = pd.read_csv("data/sales.csv")
ab = pd.read_csv("data/ab_test.csv")
houses = pd.read_csv("data/houses.csv")
sensors = pd.read_csv("data/sensors.csv")
customers = pd.read_csv("data/customers.csv")
I want to… Use… Notes
invert a conditional probability P(A∣B)P(A \mid B) Bayes’ theorem P(B∣A)P(A)P(B)\frac{P(B \mid A)P(A)}{P(B)} always track the base rate P(A)P(A)
model overdispersed event counts (Var>Mean\mathrm{Var} > \text{Mean}) Negative Binomial (stats.nbinom) Poisson assumes Var=Mean\mathrm{Var} = \text{Mean}
update a conversion rate with Beta–Binomial Beta(α+k, β+n−k)\mathrm{Beta}(\alpha + k, \, \beta + n - k) conjugate; closed-form posterior
update an event rate with Gamma–Poisson Gamma(α+∑ki, rate β+T)\mathrm{Gamma}(\alpha + \sum k_i, \, \text{rate } \beta + T) scipy.stats.gamma(a, scale=1/rate)
Bayesian A/B probability treatment beats control Monte Carlo draws from both Beta posteriors also compute expected loss
shrink noisy small-sample averages toward a prior empirical Bayes / hierarchical shrinkage α0+kα0+β0+n\frac{\alpha_0 + k}{\alpha_0 + \beta_0 + n}
connect Ridge / Lasso to Bayesian priors MAP with Gaussian prior ⇒\Rightarrow L2, Laplace ⇒\Rightarrow L1 λ=σ2/τ2\lambda = \sigma^2 / \tau^2 for Ridge
sample a non-conjugate posterior Metropolis–Hastings MCMC tune proposal width for ~23–44% accept
measure uncertainty of a discrete distribution Shannon entropy stats.entropy(p, base=2) bits (base 2) or nats (base ee)
measure distribution drift PP vs. QQ KL rel_entr(p, q).sum() or JS jensenshannon(p, q)**2 JS is symmetric and finite on zeros
rank nonlinear feature–target dependence mutual_info_classif / mutual_info_regression I(X;Y)=0I(X; Y) = 0 iff independent
Rule Formula Condition / Note
Complement P(Ac)=1−P(A)P(A^c) = 1 - P(A)
Addition (inclusion–exclusion) P(A∪B)=P(A)+P(B)−P(A∩B)P(A \cup B) = P(A) + P(B) - P(A \cap B) subtract overlap unless disjoint
Conditional probability P(A∣B)=P(A∩B)/P(B)P(A \mid B) = P(A \cap B) / P(B) requires P(B)>0P(B) > 0
Product (chain) rule P(A∩B)=P(A∣B)P(B)P(A \cap B) = P(A \mid B) P(B) equals P(A)P(B)P(A)P(B) iff independent
Law of total probability P(B)=∑iP(B∣Ai)P(Ai)P(B) = \sum_i P(B \mid A_i) P(A_i) {Ai}\{A_i\} partitions the sample space
Bayes’ theorem P(A∣B)=P(B∣A)P(A)P(B)P(A \mid B) = \frac{P(B \mid A) P(A)}{P(B)} posterior ∝\propto likelihood ×\times prior
Linearity of expectation E[aX+bY]=aE[X]+bE[Y]\mathbb{E}[aX + bY] = a\mathbb{E}[X] + b\mathbb{E}[Y] holds even when X,YX, Y are dependent
Variance identity Var(X)=E[X2]−(E[X])2\mathrm{Var}(X) = \mathbb{E}[X^2] - (\mathbb{E}[X])^2 Var(aX+b)=a2Var(X)\mathrm{Var}(aX + b) = a^2 \mathrm{Var}(X)
Sum of two random variables Var(X+Y)=Var(X)+Var(Y)+2 Cov(X,Y)\mathrm{Var}(X + Y) = \mathrm{Var}(X) + \mathrm{Var}(Y) + 2\,\mathrm{Cov}(X, Y) Cov=0\mathrm{Cov} = 0 if independent
Law of total expectation E[Y]=E[E[Y∣X]]\mathbb{E}[Y] = \mathbb{E}[\mathbb{E}[Y \mid X]] useful for hierarchical models
Family Support PMF / PDF Mean Variance scipy.stats call
Bernoulli(pp) {0,1}\{0, 1\} pk(1−p)1−kp^k(1-p)^{1-k} pp p(1−p)p(1-p) stats.bernoulli(p)
Binomial(n,pn, p) 0..n0..n (nk)pk(1−p)n−k\binom{n}{k}p^k(1-p)^{n-k} npnp np(1−p)np(1-p) stats.binom(n, p)
Poisson(λ\lambda) 0,1,…0, 1, \dots λke−λ/k!\lambda^k e^{-\lambda} / k! λ\lambda λ\lambda stats.poisson(mu=lam)
Geometric(pp) 1,2,…1, 2, \dots (1−p)k−1p(1-p)^{k-1} p 1/p1/p (1−p)/p2(1-p)/p^2 stats.geom(p)
Neg. Binomial(r,pr, p) 0,1,…0, 1, \dots (k+r−1k)pr(1−p)k\binom{k+r-1}{k} p^r (1-p)^k r(1−p)/pr(1-p)/p r(1−p)/p2r(1-p)/p^2 stats.nbinom(r, p)
Multinomial(n,pn, \mathbf{p}) ∑ki=n\sum k_i = n n!∏ki!∏piki\frac{n!}{\prod k_i!} \prod p_i^{k_i} npin p_i npi(1−pi)n p_i(1-p_i) stats.multinomial(n, p)
Uniform(a,ba, b) [a,b][a, b] 1/(b−a)1 / (b - a) (a+b)/2(a+b)/2 (b−a)2/12(b-a)^2/12 stats.uniform(loc=a, scale=b-a)
Exponential(λ\lambda) [0,∞)[0, \infty) λe−λx\lambda e^{-\lambda x} 1/λ1/\lambda 1/λ21/\lambda^2 stats.expon(scale=1/lam)
Gamma(α,β\alpha, \beta rate) (0,∞)(0, \infty) βαΓ(α)xα−1e−βx\frac{\beta^\alpha}{\Gamma(\alpha)} x^{\alpha-1} e^{-\beta x} α/β\alpha/\beta α/β2\alpha/\beta^2 stats.gamma(a=alpha, scale=1/beta)
Beta(α,β\alpha, \beta) (0,1)(0, 1) xα−1(1−x)β−1B(α,β)\frac{x^{\alpha-1}(1-x)^{\beta-1}}{B(\alpha, \beta)} αα+β\frac{\alpha}{\alpha+\beta} αβ(α+β)2(α+β+1)\frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)} stats.beta(alpha, beta)
Normal(μ,σ2\mu, \sigma^2) R\mathbb{R} 1σ2πe−(x−μ)22σ2\frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{(x-\mu)^2}{2\sigma^2}} μ\mu σ2\sigma^2 stats.norm(loc=mu, scale=sigma)
Log-normal(μ,σ2\mu, \sigma^2) (0,∞)(0, \infty) 1xσ2πe−(ln⁡x−μ)22σ2\frac{1}{x\sigma\sqrt{2\pi}} e^{-\frac{(\ln x - \mu)^2}{2\sigma^2}} eμ+σ2/2e^{\mu + \sigma^2/2} (eσ2−1)e2μ+σ2(e^{\sigma^2}-1)e^{2\mu+\sigma^2} stats.lognorm(s=sigma, scale=np.exp(mu))
daily_orders = sales.groupby("order_date")["order_id"].nunique().to_numpy()
mu, var = float(daily_orders.mean()), float(daily_orders.var(ddof=1))
# Method-of-moments Negative Binomial fit: var = mu + mu^2 / r
r_nb = mu**2 / (var - mu)
p_nb = r_nb / (r_nb + mu)
ll_pois = float(stats.poisson(mu=mu).logpmf(daily_orders).sum())
ll_nb = float(stats.nbinom(r_nb, p_nb).logpmf(daily_orders).sum())
print(f"daily orders: mean={mu:.2f}, var={var:.2f}, dispersion={var / mu:.2f}")
print(f"log-likelihood: Poisson={ll_pois:.1f}, NegBin={ll_nb:.1f}")
Output
daily orders: mean=20.35, var=104.04, dispersion=5.11
log-likelihood: Poisson=-3227.3, NegBin=-2597.8

A prior is conjugate to a likelihood when the posterior belongs to the same distribution family, turning Bayes’ rule into simple parameter addition.

Likelihood Prior Posterior Posterior mean
Binomial (kk successes in nn) Beta(α,β)\mathrm{Beta}(\alpha, \beta) Beta(α+k, β+n−k)\mathrm{Beta}(\alpha + k, \, \beta + n - k) α+kα+β+n\frac{\alpha + k}{\alpha + \beta + n}
Poisson (∑i=1mki\sum_{i=1}^m k_i events over mm units) Gamma(α,β)\mathrm{Gamma}(\alpha, \beta) (rate β\beta) Gamma(α+∑ki, β+m)\mathrm{Gamma}(\alpha + \sum k_i, \, \beta + m) α+∑kiβ+m\frac{\alpha + \sum k_i}{\beta + m}
Normal (known σ2\sigma^2, sample mean xˉ\bar{x}, size nn) N(μ0,τ02)\mathcal{N}(\mu_0, \tau_0^2) N(μn,τn2)\mathcal{N}(\mu_n, \tau_n^2), τn−2=τ0−2+nσ−2\tau_n^{-2} = \tau_0^{-2} + n\sigma^{-2} precision-weighted average of μ0\mu_0 and xˉ\bar{x}
Multinomial (counts c1,…,cKc_1, \dots, c_K) Dirichlet(α1,…,αK)\mathrm{Dirichlet}(\alpha_1, \dots, \alpha_K) Dirichlet(α1+c1,…,αK+cK)\mathrm{Dirichlet}(\alpha_1 + c_1, \dots, \alpha_K + c_K) αj+cj∑i(αi+ci)\frac{\alpha_j + c_j}{\sum_i (\alpha_i + c_i)}
summary = ab.groupby("group")["converted"].agg(["sum", "count"])
kc, nc = int(summary.loc["control", "sum"]), int(summary.loc["control", "count"])
kt, nt = int(summary.loc["treatment", "sum"]), int(summary.loc["treatment", "count"])
# Weakly informative Beta(1, 1) prior
post_c = stats.beta(1 + kc, 1 + nc - kc)
post_t = stats.beta(1 + kt, 1 + nt - kt)
rng = np.random.default_rng(42)
sc = post_c.rvs(50_000, random_state=rng)
st = post_t.rvs(50_000, random_state=rng)
prob_t_wins = float(np.mean(st > sc))
exp_loss_ship_t = float(np.mean(np.maximum(sc - st, 0.0)))
ci_lift = np.quantile(st - sc, [0.025, 0.975])
print(f"P(treatment > control) = {prob_t_wins:.4f}")
print(f"95% credible interval (t - c): [{ci_lift[0]:.4f}, {ci_lift[1]:.4f}]")
print(f"expected loss if shipping treatment: {exp_loss_ship_t:.6f}")
Output
P(treatment > control) = 0.9937
95% credible interval (t - c): [0.0034, 0.0277]
expected loss if shipping treatment: 0.000013
  • MLE (Maximum Likelihood): θ^MLE=arg⁡max⁡θ∑iln⁡p(xi∣θ)\hat{\theta}_{\text{MLE}} = \arg\max_\theta \sum_i \ln p(x_i \mid \theta).
  • MAP (Maximum A Posteriori): θ^MAP=arg⁡max⁡θ[∑iln⁡p(xi∣θ)+ln⁡p(θ)]\hat{\theta}_{\text{MAP}} = \arg\max_\theta \left[\sum_i \ln p(x_i \mid \theta) + \ln p(\theta)\right].
Noise likelihood Weight prior p(w)p(w) Negative log-posterior objective Equivalent ML model
Gaussian N(Xw,σ2I)\mathcal{N}(Xw, \sigma^2 I) flat (improper) 12∥y−Xw∥22\frac{1}{2}\Vert y - Xw \Vert_2^2 OLS linear regression
Gaussian N(Xw,σ2I)\mathcal{N}(Xw, \sigma^2 I) N(0,τ2I)\mathcal{N}(0, \tau^2 I) 12∥y−Xw∥22+λ2∥w∥22\frac{1}{2}\Vert y - Xw \Vert_2^2 + \frac{\lambda}{2}\Vert w \Vert_2^2, λ=σ2/τ2\lambda = \sigma^2/\tau^2 Ridge regression (L2)
Gaussian N(Xw,σ2I)\mathcal{N}(Xw, \sigma^2 I) Laplace ∝exp⁡(−∣w∣/b)\propto \exp(-\vert w \vert / b) 12∥y−Xw∥22+λ∥w∥1\frac{1}{2}\Vert y - Xw \Vert_2^2 + \lambda \Vert w \Vert_1, λ=σ2/b\lambda = \sigma^2 / b Lasso regression (L1)
Bernoulli (logit) N(0,τ2I)\mathcal{N}(0, \tau^2 I) binary cross-entropy +12τ2∥w∥22+ \frac{1}{2\tau^2}\Vert w \Vert_2^2 L2 LogisticRegression (C=τ2C = \tau^2)
X_raw = houses[["sqft", "bedrooms", "bathrooms", "condition"]].to_numpy(dtype=float)
X = (X_raw - X_raw.mean(0)) / X_raw.std(0)
y = np.log(houses["price"].to_numpy(dtype=float))
y_c = y - y.mean()
lam = 25.0 # sigma^2 / tau^2
w_map = np.linalg.solve(X.T @ X + lam * np.eye(X.shape[1]), X.T @ y_c)
w_ridge = Ridge(alpha=lam, fit_intercept=False).fit(X, y_c).coef_
print("MAP weights: ", np.round(w_map, 5))
print("matches Ridge:", np.allclose(w_map, w_ridge))
Output
MAP weights: [ 0.33573 -0.01172 0.05283 0.10692]
matches Ridge: True

When a posterior has no conjugate closed form, Metropolis–Hastings draws correlated samples from p(θ∣D)∝p(D∣θ)p(θ)p(\theta \mid \mathcal{D}) \propto p(\mathcal{D} \mid \theta) p(\theta) without computing the normalizing constant:

  1. Propose θ′∼q(θ′∣θt)\theta' \sim q(\theta' \mid \theta_t) (symmetric random walk: θ′=θt+N(0,s2)\theta' = \theta_t + \mathcal{N}(0, s^2)).
  2. Compute log acceptance ratio log⁡α=log⁡p~(θ′)−log⁡p~(θt)\log \alpha = \log \tilde{p}(\theta') - \log \tilde{p}(\theta_t) (add +log⁡q(θt∣θ′)−log⁡q(θ′∣θt)+\log q(\theta_t \mid \theta') - \log q(\theta' \mid \theta_t) if asymmetric).
  3. Accept θt+1=θ′\theta_{t+1} = \theta' if log⁡U<log⁡α\log U < \log \alpha for U∼Uniform(0,1)U \sim \mathrm{Uniform}(0, 1), else keep θt+1=θt\theta_{t+1} = \theta_t.
Diagnostic Healthy target What to fix if off
Burn-in discard initial 10–25% of draws trace still trending away from start
Acceptance rate (1D / multi-D) ~40–50% (1D), ~23% (high-D) too high ⇒\Rightarrow widen step; too low ⇒\Rightarrow shrink step
Trace plot fuzzy horizontal caterpillar sticky plateaus ⇒\Rightarrow poor mixing; reparameterize
Split-R^\hat{R} (multi-chain) <1.01< 1.01 run longer or fix multimodal parameterization
def log_post(theta: float) -> float:
if not (0.0 < theta < 1.0):
return -np.inf
return float(
stats.beta.logpdf(theta, 2.0, 2.0) + stats.binom.logpmf(18, 50, theta)
)
chain = np.empty(6_000)
cur, accepted = 0.5, 0
cur_lp = log_post(cur)
for i in range(len(chain)):
prop = cur + float(rng.normal(0.0, 0.15))
prop_lp = log_post(prop)
if np.log(rng.random()) < prop_lp - cur_lp:
cur, cur_lp = prop, prop_lp
accepted += 1
chain[i] = cur
draws = chain[1_000:] # discard burn-in
exact = stats.beta(2 + 18, 2 + 32)
print(f"accept rate: {accepted / len(chain):.3f}")
print(f"MCMC mean={draws.mean():.4f}, std={draws.std():.4f}")
print(f"Exact mean={exact.mean():.4f}, std={exact.std():.4f}")
Output
accept rate: 0.462
MCMC mean=0.3734, std=0.0681
Exact mean=0.3704, std=0.0651
Measure Formula (discrete) Properties & ML use Python
Shannon entropy H(P)=−∑xP(x)log⁡P(x)H(P) = -\sum_x P(x)\log P(x) ≥0\ge 0; decision-tree impurity, coding lower bound stats.entropy(p, base=2)
Cross-entropy H(P,Q)=−∑xP(x)log⁡Q(x)H(P, Q) = -\sum_x P(x)\log Q(x) =H(P)+DKL(P∥Q)= H(P) + D_{\mathrm{KL}}(P \parallel Q); classification loss -np.sum(p * np.log(q))
KL divergence DKL(P∥Q)=∑xP(x)log⁡P(x)Q(x)D_{\mathrm{KL}}(P \parallel Q) = \sum_x P(x)\log \frac{P(x)}{Q(x)} ≥0\ge 0, asymmetric; ∞\infty if Q(x)=0Q(x)=0 where P(x)>0P(x)>0 rel_entr(p, q).sum()
Jensen–Shannon divergence JSD(P,Q)=12DKL(P∥M)+12DKL(Q∥M)\mathrm{JSD}(P, Q) = \frac{1}{2}D_{\mathrm{KL}}(P \parallel M) + \frac{1}{2}D_{\mathrm{KL}}(Q \parallel M) symmetric, bounded in [0,ln⁡2][0, \ln 2] (or [0,1][0, 1] base 2) jensenshannon(p, q) ** 2
Mutual information I(X;Y)=DKL(PX,Y∥PXPY)I(X; Y) = D_{\mathrm{KL}}(P_{X,Y} \parallel P_X P_Y) ≥0\ge 0; captures linear and nonlinear dependence mutual_info_classif(X, y)
s3 = sensors.loc[sensors["sensor_id"] == "S3", ["timestamp", "temperature_c"]].dropna()
w1 = s3.loc[s3["timestamp"] < "2024-05-08", "temperature_c"].to_numpy()
w2 = s3.loc[s3["timestamp"] >= "2024-05-08", "temperature_c"].to_numpy()
edges = np.linspace(min(w1.min(), w2.min()), max(w1.max(), w2.max()), 16)
p1 = np.histogram(w1, bins=edges)[0] + 1e-6 # Laplace smoothing avoids log(0)
p2 = np.histogram(w2, bins=edges)[0] + 1e-6
p1, p2 = p1 / p1.sum(), p2 / p2.sum()
kl_nats = float(rel_entr(p1, p2).sum())
js_div = float(jensenshannon(p1, p2) ** 2)
mi_cols = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
mi = mutual_info_classif(
customers[mi_cols], customers["churned"], random_state=42
)
print(f"S3 drift (week 1 vs week 2): KL={kl_nats:.3f} nats, JSD={js_div:.3f}")
print("MI:", ", ".join(f"{c}={v:.4f}" for c, v in zip(mi_cols, mi)))
Output
S3 drift (week 1 vs week 2): KL=2.820 nats, JSD=0.212
MI: tenure_months=0.0751, monthly_charges=0.0133, support_tickets=0.0196, logins_last_30d=0.0023
Trap Symptom Fix
confusing scale with rate in stats.gamma / stats.expon posterior mean is inverted (αβ\alpha\beta instead of α/β\alpha/\beta) pass scale=1 / rate
ignoring base rate in Bayes’ theorem “95% accurate test” looks like 95% disease probability compute P(D∣+)P(D \mid +) using prevalence P(D)P(D)
reading a 95% confidence interval as a 95% credible interval wrong interpretation of frequentist coverage use a Bayesian posterior for P(θ∈[a,b]∣data)P(\theta \in [a, b] \mid \text{data})
computing likelihoods as raw products ∏p(xi)\prod p(x_i) underflows to 0.0 at n≈500n \approx 500 sum log-likelihoods (logpdf / logpmf)
passing unsmoothed histograms to rel_entr(p, q) returns inf whenever any bin has q == 0 add small pseudocounts or use jensenshannon(p, q) ** 2
treating KL divergence as symmetric DKL(P∥Q)D_{\text{KL}}(P \parallel Q) differs sharply from DKL(Q∥P)D_{\text{KL}}(Q \parallel P) document reference PP vs. model QQ, or use JSD
forgetting to square jensenshannon(p, q) SciPy returns JS distance (JSD\sqrt{\text{JSD}}), not divergence square it for divergence; pass base=2 for bits
skipping burn-in or acceptance checks in MCMC biased posterior mean or stuck chain discard burn-in, check acceptance rate and trace plots
forgetting stats.nbinom(r, p) counts failures wrong mean when using standard textbook (r,p)(r, p) check mean = r * (1 - p) / p, var = r * (1 - p) / p**2

Causal inference, GLMs and experimentation

Section titled “Causal inference, GLMs and experimentation”

Prediction asks what happens when you observe XX; causal inference asks what happens when you intervene on XX. This reference summarizes causal DAG rules, A/B testing safeguards (SRM, peeking, CUPED, bandits), observational estimators (IPW, DiD), statsmodels Generalized Linear Models, and Kaplan–Meier retention curves. All blocks share one session using data/ab_test.csv and data/customers.csv:

import numpy as np
import pandas as pd
from scipy import stats
from sklearn.linear_model import LogisticRegression
import statsmodels.api as sm
import statsmodels.formula.api as smf
ab = pd.read_csv("data/ab_test.csv")
customers = pd.read_csv("data/customers.csv")
I want to… Use… Notes
decide which variables to adjust for in a causal model draw a causal DAG first adjust confounders; never adjust colliders or mediators (for total effect)
check if an A/B test traffic split is broken stats.chisquare(counts, expected) Sample Ratio Mismatch (SRM); stop if p<0.001p < 0.001
shrink A/B test variance using a pre-period metric CUPED Ycuped=Y−θ(X−Xˉ)Y_{\text{cuped}} = Y - \theta (X - \bar{X}) θ=Cov(Y,X)/Var(X)\theta = \mathrm{Cov}(Y, X) / \mathrm{Var}(X); cuts variance by 1−r21 - r^2
optimize reward while testing variants online Thompson sampling (Beta–Binomial bandit) samples from posteriors; minimizes regret
estimate ATE from observational data with measured confounders Propensity score IPW / stabilized IPW check overlap and post-weight covariate balance (SMD < 0.1)
estimate policy impact with before/after + control group Difference-in-Differences (DiD) requires parallel trends before treatment
model positive count data (Var≈Mean\mathrm{Var} \approx \text{Mean}) smf.glm(..., family=sm.families.Poisson()) np.exp(coef) is the incidence rate ratio (IRR)
model overdispersed count data (Var>Mean\mathrm{Var} > \text{Mean}) smf.glm(..., family=sm.families.NegativeBinomial(alpha=...)) or smf.negativebinomial (MLE α\alpha)
model binary outcomes with odds ratios smf.glm(..., family=sm.families.Binomial()) np.exp(coef) is the odds ratio
estimate customer retention with right-censored tenures Kaplan–Meier S^(t)=∏ti≤t(1−di/ni)\hat{S}(t) = \prod_{t_i \le t}(1 - d_i / n_i) dropping active users biases survival downward

Each unit ii has two potential outcomes: Yi(1)Y_i(1) if treated (Ti=1T_i = 1) and Yi(0)Y_i(0) if untreated (Ti=0T_i = 0). We only ever observe one: Yi=TiYi(1)+(1−Ti)Yi(0)Y_i = T_i Y_i(1) + (1 - T_i) Y_i(0).

  • ATE (Average Treatment Effect): E[Y(1)−Y(0)]\mathbb{E}[Y(1) - Y(0)].
  • ATT (Average Treatment Effect on the Treated): E[Y(1)−Y(0)∣T=1]\mathbb{E}[Y(1) - Y(0) \mid T = 1].
  • Identification assumptions: SUTVA (no interference between units), Conditional Ignorability ((Y(1),Y(0))⊥T∣X(Y(1), Y(0)) \perp T \mid X, no unmeasured confounders), and Positivity (0<P(T=1∣X)<10 < P(T = 1 \mid X) < 1).
flowchart LR
    subgraph Fork["Confounder (adjust)"]
        C1["C"] --> T1["T"]
        C1 --> Y1["Y"]
    end
    subgraph Chain["Mediator (do NOT adjust for total effect)"]
        T2["T"] --> M2["M"] --> Y2["Y"]
    end
    subgraph Collider["Collider (NEVER adjust)"]
        T3["T"] --> K3["K"]
        Y3["Y"] --> K3
    end
Structure Path Natural state Conditioning on middle node Action for total effect T→YT \to Y
Fork (confounder) T←C→YT \leftarrow C \to Y open (creates spurious correlation) blocks backdoor path adjust for CC
Chain (mediator) T→M→YT \to M \to Y open (carries causal effect) blocks causal path do not adjust for MM (adjust only for direct effect)
Collider T→K←YT \to K \leftarrow Y blocked opens spurious correlation (selection bias) never adjust for KK or its descendants

Simpson’s paradox occurs when an aggregate association reverses inside subgroups. The data alone cannot tell you whether the aggregate or subgroup number is right — the DAG decides (adjust if the grouping variable is a confounder, not if it is a mediator or collider).

Experimentation: SRM, peeking, CUPED and bandits

Section titled “Experimentation: SRM, peeking, CUPED and bandits”
Technique / Trap Formula or rule Practical takeaway
Sample Ratio Mismatch (SRM) χ2\chi^2 goodness-of-fit on group counts vs. planned split if p<0.001p < 0.001, logging or randomization is broken — do not trust metrics
Optional stopping (peeking) testing repeatedly at α=0.05\alpha = 0.05 inflates Type I error to ~20–30% fix sample size upfront, or use sequential boundaries (alpha spending / always-valid p-values)
CUPED variance reduction Y∗=Y−θ(X−Xˉ)Y^* = Y - \theta(X - \bar{X}), θ=Cov(Y,X)Var(X)\theta = \frac{\mathrm{Cov}(Y, X)}{\mathrm{Var}(X)} unbiased if XX is strictly pre-treatment; Var(Y∗)=(1−r2)Var(Y)\mathrm{Var}(Y^*) = (1 - r^2)\mathrm{Var}(Y)
Epsilon-greedy bandit random arm with prob ε\varepsilon, else highest mean simple; linear regret unless εt\varepsilon_t decays
UCB1 bandit pick arg⁡max⁡a(μ^a+2ln⁡tna)\arg\max_a \left(\hat{\mu}_a + \sqrt{\frac{2 \ln t}{n_a}}\right) deterministic optimism; O(log⁡T)O(\log T) regret
Thompson sampling draw θ~a∼Posteriora\tilde{\theta}_a \sim \text{Posterior}_a; pick arg⁡max⁡aθ~a\arg\max_a \tilde{\theta}_a natural Beta–Binomial fit; low regret and robust to delayed feedback
# 1. Sample Ratio Mismatch check on data/ab_test.csv (planned 50/50 split)
counts = ab["group"].value_counts().sort_index()
srm = stats.chisquare(counts, f_exp=[len(ab) / 2, len(ab) / 2])
print(f"SRM counts={counts.to_dict()}, p={srm.pvalue:.3f}")
# 2. CUPED variance reduction with a correlated pre-experiment covariate
rng = np.random.default_rng(42)
n_sim = 2_000
x_pre = rng.normal(50.0, 10.0, n_sim)
treat = rng.integers(0, 2, n_sim)
y_post = 0.8 * x_pre + 1.2 * treat + rng.normal(0.0, 6.0, n_sim)
def diff_se(a: np.ndarray, b: np.ndarray) -> float:
return float(np.sqrt(a.var(ddof=1) / len(a) + b.var(ddof=1) / len(b)))
theta = float(np.cov(y_post, x_pre, ddof=1)[0, 1] / np.var(x_pre, ddof=1))
y_cuped = y_post - theta * (x_pre - x_pre.mean())
se_raw = diff_se(y_post[treat == 1], y_post[treat == 0])
se_cuped = diff_se(y_cuped[treat == 1], y_cuped[treat == 0])
drop = 1.0 - se_cuped / se_raw
print(f"SE raw={se_raw:.3f} vs CUPED={se_cuped:.3f} (reduction {drop:.1%})")
# 3. Thompson sampling over 3 arms (true rates 0.08, 0.11, 0.14)
true_p = [0.08, 0.11, 0.14]
alpha, beta = np.ones(3), np.ones(3)
for _ in range(1_500):
arm = int(np.argmax(rng.beta(alpha, beta)))
reward = int(rng.random() < true_p[arm])
alpha[arm] += reward
beta[arm] += 1 - reward
pulls = (alpha + beta - 2).astype(int).tolist()
print("Thompson sampling pulls per arm:", pulls)
Output
SRM counts={'control': 5002, 'treatment': 4998}, p=0.968
SE raw=0.447 vs CUPED=0.266 (reduction 40.4%)
Thompson sampling pulls per arm: [112, 683, 705]
Method Core idea Key assumption Watch out
Regression adjustment include confounders XX in outcome model correct functional form + no unmeasured confounders extrapolates if treated/control do not overlap
Propensity score matching pair treated and control units with similar e(x)=P(T=1∣X=x)e(x) = P(T=1 \mid X=x) ignorability + common support discards unmatched units (estimates ATT)
IPW (Horvitz–Thompson / Hájek) weight treated by 1/e(x)1/e(x), control by 1/(1−e(x))1/(1-e(x)) positivity (0<e(x)<10 < e(x) < 1) clip extreme propensities; check post-weight SMD < 0.1
Doubly Robust (AIPW) combines outcome model + IPW consistent if either model is right preferred default in modern observational studies
Difference-in-Differences (DiD) (YˉT,post−YˉT,pre)−(YˉC,post−YˉC,pre)(\bar{Y}_{T,\text{post}} - \bar{Y}_{T,\text{pre}}) - (\bar{Y}_{C,\text{post}} - \bar{Y}_{C,\text{pre}}) parallel trends without treatment check pre-treatment trend slopes; cluster SEs by unit
# Estimate the effect of has_autopay on churned using Propensity Score IPW
df = customers.copy()
X_cov = pd.get_dummies(
df[["age", "tenure_months", "monthly_charges", "payment_method", "contract"]],
drop_first=True,
dtype=float,
)
T = df["has_autopay"].to_numpy(dtype=float)
Y = df["churned"].to_numpy(dtype=float)
ps = LogisticRegression(max_iter=1_000).fit(X_cov, T).predict_proba(X_cov)[:, 1]
ps = np.clip(ps, 0.05, 0.95)
w1 = T / ps
w0 = (1.0 - T) / (1.0 - ps)
naive_ate = float(Y[T == 1].mean() - Y[T == 0].mean())
ipw_ate = float(np.sum(w1 * Y) / np.sum(w1) - np.sum(w0 * Y) / np.sum(w0)) # Hajek
# Check standardized mean difference (SMD) of electronic_check before vs after IPW
ec = (df["payment_method"] == "electronic_check").to_numpy(dtype=float)
sd_pool = float(np.sqrt(0.5 * (ec[T == 1].var() + ec[T == 0].var())))
smd_before = (ec[T == 1].mean() - ec[T == 0].mean()) / sd_pool
smd_after = (
np.sum(w1 * ec) / np.sum(w1) - np.sum(w0 * ec) / np.sum(w0)
) / sd_pool
print(f"naive diff={naive_ate:.4f}, IPW ATE={ipw_ate:.4f}")
print(f"electronic_check SMD: before={smd_before:.3f}, after={smd_after:.3f}")
Output
naive diff=-0.0493, IPW ATE=-0.0296
electronic_check SMD: before=-1.136, after=-0.007

A GLM connects the linear predictor η=Xβ\eta = X\beta to the expected outcome μ=E[Y∣X]\mu = \mathbb{E}[Y \mid X] via a link function g(μ)=ηg(\mu) = \eta and a distribution from the exponential dispersion family.

Outcome type statsmodels family Canonical link g(μ)g(\mu) Inverse link μ=g−1(η)\mu = g^{-1}(\eta) Interpretation of eβje^{\beta_j}
Continuous, symmetric sm.families.Gaussian() identity μ\mu η\eta additive unit change (βj\beta_j)
Binary / proportion sm.families.Binomial() logit ln⁡μ1−μ\ln\frac{\mu}{1-\mu} σ(η)\sigma(\eta) odds ratio (OR)
Counts (Var≈μ\mathrm{Var} \approx \mu) sm.families.Poisson() log ln⁡μ\ln \mu eηe^\eta incidence rate ratio (IRR)
Overdispersed counts (Var=μ+αμ2\mathrm{Var} = \mu + \alpha\mu^2) sm.families.NegativeBinomial(alpha=...) log ln⁡μ\ln \mu eηe^\eta incidence rate ratio (IRR)
Positive right-skewed (revenue, duration) sm.families.Gamma(sm.families.links.Log()) log (preferred over inverse) eηe^\eta multiplicative mean ratio

Compare nested or non-nested GLMs on the same data with AIC (2k−2ℓ2k - 2\ell) and BIC (kln⁡n−2ℓk\ln n - 2\ell) — lower is better — and check Pearson dispersion (χPearson2/dfresid\chi^2_{\text{Pearson}} / \text{df}_{\text{resid}}): values well above 1.01.0 in Poisson regression signal overdispersion.

formula = "support_tickets ~ C(contract) + monthly_charges + tenure_months"
pois = smf.glm(formula, data=customers, family=sm.families.Poisson()).fit()
nb = smf.negativebinomial(formula, data=customers).fit(disp=False)
dispersion = float(pois.pearson_chi2 / pois.df_resid)
irrs = np.exp(nb.params.drop(["Intercept", "alpha"]))
print(f"Poisson dispersion={dispersion:.3f}, AIC={pois.aic:.1f}")
print(f"NegBin alpha={nb.params['alpha']:.3f}, AIC={nb.aic:.1f}")
for name, val in irrs.items():
print(f" IRR {name}: {val:.3f}")
Output
Poisson dispersion=1.056, AIC=14329.7
NegBin alpha=0.043, AIC=14324.7
IRR C(contract)[T.one-year]: 0.937
IRR C(contract)[T.two-year]: 0.986
IRR monthly_charges: 0.993
IRR tenure_months: 0.994

When modeling time to an event (churn, failure, recovery), active subjects whose event has not happened by the snapshot date are right-censored (event = 0). Dropping them or treating their current tenure as a churn time biases retention severely downward.

The Kaplan–Meier estimator computes the survival function S(t)=P(T>t)S(t) = P(T > t) from event times tit_i with did_i events out of nin_i subjects still at risk just before tit_i:

S^(t)=∏ti≤t(1−dini),Var^(S^(t))≈S^(t)2∑ti≤tdini(ni−di)(Greenwood)\hat{S}(t) = \prod_{t_i \le t} \left(1 - \frac{d_i}{n_i}\right), \qquad \widehat{\mathrm{Var}}(\hat{S}(t)) \approx \hat{S}(t)^2 \sum_{t_i \le t} \frac{d_i}{n_i (n_i - d_i)} \quad (\text{Greenwood})
def kaplan_meier(durations: np.ndarray, events: np.ndarray) -> pd.DataFrame:
"""Right-censored Kaplan-Meier survival curve with Greenwood SE."""
order = np.argsort(durations)
t_all, e_all = durations[order], events[order]
times = np.unique(t_all[e_all == 1])
surv, var_sum, rows = 1.0, 0.0, []
for t in times:
n_risk = int(np.sum(t_all >= t))
d_events = int(np.sum((t_all == t) & (e_all == 1)))
surv *= 1.0 - d_events / n_risk
if n_risk > d_events:
var_sum += d_events / (n_risk * (n_risk - d_events))
se = surv * np.sqrt(var_sum)
rows.append((int(t), n_risk, d_events, surv, se))
return pd.DataFrame(rows, columns=["t", "n_risk", "events", "S", "se"])
for contract in ["month-to-month", "one-year", "two-year"]:
sub = customers[customers["contract"] == contract]
km = kaplan_meier(sub["tenure_months"].to_numpy(), sub["churned"].to_numpy())
s12 = float(km.loc[km["t"] <= 12, "S"].iloc[-1])
s36 = float(km.loc[km["t"] <= 36, "S"].iloc[-1])
print(f"{contract:<15} S(12m)={s12:.3f}, S(36m)={s36:.3f}")
Output
month-to-month S(12m)=0.742, S(36m)=0.557
one-year S(12m)=0.974, S(36m)=0.888
two-year S(12m)=0.995, S(36m)=0.972
Trap Symptom Fix
controlling for every available column in a causal regression opens collider bias or blocks mediators, reversing the sign select covariates from a causal DAG, not by p-value or R2R^2
peeking daily at an A/B test and stopping at p<0.05p < 0.05 false-positive rate climbs past 20% pre-commit sample size or use sequential testing
using post-treatment metrics as the CUPED covariate XX biases treatment effect estimate use only strictly pre-experiment covariates
ignoring extreme propensity scores (e(x)≈0e(x) \approx 0 or 11) in IPW one unit gets weight 200 and dominates the ATE clip/trim propensities, use Hájek weights, check overlap
running DiD without checking pre-treatment trends captures pre-existing divergence as a fake policy effect plot and test pre-period parallel trends
trusting Poisson GLM standard errors when dispersion >1.5> 1.5 p-values are far too small (false significance) switch to Negative Binomial (smf.negativebinomial) or quasi-Poisson
using sm.families.Gamma() with its default inverse link convergence errors or hard-to-interpret coefficients pass sm.families.Gamma(sm.families.links.Log())
exponentiating logistic coefficients as “relative risk” overstates lift when base rate >10%> 10\% eβe^\beta is an odds ratio, not a risk ratio
computing mean tenure on churned customers only ignores active customers (right censoring), underestimating retention use Kaplan–Meier or Cox proportional hazards