▚ The AI Engineer's Field Manual
Module 01c · Act I — Foundations

Python for Data — NumPy, pandas, Plots and Honest EDA

"A messy export is not data yet. It becomes data when every column has one type, one meaning, and a note on how far to trust it."

~5 hours Builds on: Module 01, A1, Module 01b Tools: NumPy 2.5 · pandas 3 · matplotlib · seaborn · Pydantic v2 · Parquet Job-spec line it unlocks: "Python data stack: pandas, NumPy, EDA, data cleaning and visualisation"

01 · The hookFifty Thousand Rows Nobody Has Opened

Field report · Internal memo, Monday 28 September 2026

"Marcus asked me one question on Friday: why did weekend cancellations jump? Our dashboard says Friday-to-Sunday cancellations went from 10.5% of trips in the four weeks to 30 August to 13.0% in the four weeks since. That is about 300 extra cancelled trips in a pilot of five cities. We open in fifteen more cities next quarter.

The board meets Thursday. Marcus wants to either roll back the new weekend pricing or hire drivers, and he cannot afford to be wrong about which. The only evidence is the trips export: 50,000 rows from three systems that were never meant to be joined. Nobody has opened it. I have until Wednesday evening."

— Priya Nair, Head of Operations at "RideNow"

RideNow is a city ride-hailing company, and this chapter is Priya's week. Her question is not hard to say. It is hard to answer, because the file she has is not yet a table of trips. It is a pile of text that looks like one.

The timestamps come in four spellings and two time zones. One city has twenty-one spellings across its trips. Some fares are negative, some trips are thousands of kilometres long, and about one row in fifty is a repeat. If she averages anything, she averages the damage.

So her week has a shape, and so does this chapter. She must load the file safely, clean it with a checklist she can defend, look at it with a repeatable method, and hand Marcus five findings he can check. Every section below is the next day of that week.

trips_raw.csv 50,000 rows 1 mixed time formats, 21 city spellings clean_trips.py 49,000 rows 2 one clock, 5 cities, no duplicate trips eda_report.py 5 findings 3 a plot and a caveat for every finding findings.json 5 records 4 each record checked by Pydantic Marcus's dashboard: Fri-Sun cancel rate 10.5% -> 13.0%. Why?
Fig. 1.1 — The whole chapter in one line: RideNow's raw export goes in, five checked findings come out, and the CEO's single dashboard number is the question that starts it.
  1. Raw export. 50,000 rows exactly as three different systems wrote them: three time formats, two time zones, 21 spellings of 5 cities. Nothing here can be trusted yet.
  2. Cleaning. 49,000 rows are left. 1,000 repeated trips are gone and every column has one type and one meaning. The accent colour marks the step this chapter builds first.
  3. Analysis. Five questions, each answered with a plot, a sentence and a caveat. The caveat says what the plot does not prove.
  4. Structured output. The five findings are saved as JSON and checked by a schema, so a program (or an LLM, later) can read them without guessing.
You already know this

You have written ETL code, parsed awkward API responses, and fixed timezone bugs. This chapter is the same job with a different toolbox. A NumPy array is a typed, contiguous buffer, like a Java double[] or a Go slice. A pandas DataFrame is an in-memory table with a query API, much like a SQL result set you can index into. Cleaning is input validation. EDA is exploratory testing of the data instead of the code.

What is new is the habit. In software, a bad input raises an exception. In data, a bad input quietly becomes a wrong number in a slide deck. The checklist in this chapter is how you make bad inputs loud.

The big picture appears twice. Fig. 1.1 above is the abstract pipeline. The table below is the same four stages with the real files, calls and numbers you will meet.

The same pipeline, stage by stage, with the real files and what flows out of each
StageNaive versionProduction versionWhat flows out
1. Loadpd.read_csv(path) and let pandas guessread_csv(dtype=str), then decide every type yourself50,000 rows, every column text
2. CleanDrop any row that looks oddA five-step checklist in clean_trips.py that counts each fix49,000 typed rows in trips_clean.parquet
3. ExplorePlot everything, pick the pretty chartQuestion, plot, finding, caveat, five times in eda_report.pyFive figures and five sentences with numbers
4. Hand overPaste a screenshot into chatPydantic-checked findings.jsonFive records a program can read

Several words in that table, such as dtype, Parquet and Pydantic, have not been explained yet. You are not expected to know them. Each gets its own small example before it gets used for real.

02 · NumPyArrays: Do It to the Whole Column

It is Monday night. Priya has the export and one question. Before she touches the messy file, she wants the one tool every other Python data library stands on, because the numbers in it will be arrays of distances, fares and waits. Tuesday's cleaning and Wednesday's plots both assume she can talk to a whole column at once.

A NumPy array is a fixed-size, single-type block of numbers that you can do arithmetic on all at once, without writing a loop. Without it, every calculation on a million numbers is a slow Python loop that is also easier to get wrong.

Start with four numbers

Before the big comparison, here is the smallest NumPy program worth running. It holds four trip distances, prices them, and picks out the long ones. Read the output line by line against the code.

Step-by-step: what tiny_numpy.py does, in plain English
  1. import numpy as np loads the library under its usual short name.
  2. np.array([...]) turns a Python list into one array. All four numbers share one type, here 64-bit decimals.
  3. 40 + 11.5 * km multiplies every element by 11.5 and adds 40 to every element. No loop is written; the loop happens inside NumPy.
  4. .shape, .dtype and .mean() report the array's size, its number type and its average.
  5. km > 6 compares every element with 6 and gives an array of True and False. Using that array inside square brackets keeps only the True positions. This is called a boolean mask.
tiny_numpy.pyruns offline
# tiny_numpy.py -- the smallest NumPy program: four distances, one array, no loop.
# pip install "numpy>=2.5,<2.6"
import numpy as np

km = np.array([2.0, 5.5, 8.0, 12.5])       # four trip distances
fare = 40 + 11.5 * km                        # applied to every element at once
print(fare)
print("shape:", km.shape, "| dtype:", km.dtype, "| mean fare:", fare.mean())
print("trips over 6 km:", km > 6, "->", km[km > 6])
what it printed
[ 63.   103.25 132.   183.75]
shape: (4,) | dtype: float64 | mean fare: 120.5
trips over 6 km: [False False  True  True] -> [ 8.  12.5]

Read the output. The first line is four fares, one per distance: 2 km costs 63, 12.5 km costs 183.75. The shape (4,) means "one direction, four items". The dtype float64 says each number is a 64-bit decimal. The last line shows the mask [False False True True] picking out 8.0 and 12.5. You will use this mask idea in every filter in this chapter.

Why not just use a Python list?

A Python list can hold anything, so each number is a full object with a type tag, and Python checks that tag on every step. A NumPy array holds one type packed side by side, so one compiled loop can race through it. The next program prices one million trips both ways and times them.

The program below uses rng.lognormal, astype and allclose. You have not met them. Guess what each line does first, then read the answers. Nothing here is a trick question.

Sharpen your pencil

Ten lines from numpy_speed.py are listed below. Three are explained for you. Write what you think each blank line does, in plain English, before you open the answers.

km = rng.lognormal(1.75, 0.55, 1_000_000)make one million fake trip distances; most are near 6 km and a few are very long
print("dtype:", km.dtype, "| total MB:", km.nbytes / 1e6)
loop_fares = [40 + 11.5 * k for k in km.tolist()]price every trip with a Python loop, one number at a time
t0 = time.perf_counter()
vec_fares = 40 + 11.5 * kmthe same prices in one array expression
np.allclose(loop_fares, vec_fares)
km32 = km.astype(np.float32)
np.array([120, 100], dtype=np.int8) + np.array([10, 100], dtype=np.int8)
base_fare = np.array([[40.0], [45.0], [50.0]])
price_for_10km = base_fare + per_km * 10
Check your answers
km = rng.lognormal(1.75, 0.55, 1_000_000)makes one million fake trip distances; most are near 6 km and a few are very long
print("dtype:", km.dtype, "| total MB:", km.nbytes / 1e6)prints the number type (float64) and the memory used: 1,000,000 numbers times 8 bytes = 8 MB
loop_fares = [40 + 11.5 * k for k in km.tolist()]prices every trip with a Python loop, one number at a time
t0 = time.perf_counter()starts a stopwatch; the next stopwatch reading minus this one is the elapsed time
vec_fares = 40 + 11.5 * kmthe same prices in one array expression
np.allclose(loop_fares, vec_fares)checks the two answers agree to within tiny rounding; this proves the fast way did not change the result
km32 = km.astype(np.float32)copies the array into a smaller box: 4 bytes per number instead of 8
np.array([120, 100], dtype=np.int8) + ...adds two tiny whole-number arrays where each number must fit in one byte; the results overflow and wrap
base_fare = np.array([[40.0], [45.0], [50.0]])makes a column: three rows, one column, shape (3, 1)
price_for_10km = base_fare + per_km * 10adds a (3, 1) column to a (1, 4) row, which broadcasts into a (3, 4) table

If you got the first three right and guessed the rest roughly, you already read NumPy fluently. The unfamiliar part is only the shapes, and the next sections show them.

Step-by-step: what numpy_speed.py does, in plain English
  1. np.random.default_rng(7) makes a seeded random generator, so the same distances come out every run.
  2. It draws one million trip distances and prints their type and memory size.
  3. It starts a stopwatch, prices every distance with a list comprehension (the Python loop), and stops the stopwatch.
  4. It does the same pricing as one array expression and times that too.
  5. It prints both times and the ratio, then checks the two answers match with np.allclose.
  6. It converts the distances to float32 and reports the memory and the largest rounding error.
  7. It adds two int8 arrays to show silent overflow.
  8. It builds a (3, 1) column and a (1, 4) row and adds them, to show broadcasting.
numpy_speed.pyruns offline
# numpy_speed.py -- why NumPy exists: the same sum, a Python loop versus one array operation.
# pip install "numpy>=2.5,<2.6"
import time

import numpy as np

rng = np.random.default_rng(7)
km = rng.lognormal(1.75, 0.55, 1_000_000)            # one million trip distances, float64
print("dtype:", km.dtype, "| bytes per number:", km.itemsize, "| total MB:", km.nbytes / 1e6)

# the loop: price each trip = 40 + 11.5 per km, one Python object at a time
t0 = time.perf_counter()
loop_fares = [40 + 11.5 * k for k in km.tolist()]
loop_s = time.perf_counter() - t0

# the array: the same arithmetic, done for all million at once inside compiled code
t0 = time.perf_counter()
vec_fares = 40 + 11.5 * km
vec_s = time.perf_counter() - t0
print(f"loop {loop_s*1000:.1f} ms | vectorised {vec_s*1000:.2f} ms | speedup about {loop_s/vec_s:.0f}x")
print("same answer:", np.allclose(loop_fares, vec_fares))

# dtypes: the same numbers in a smaller box
km32 = km.astype(np.float32)
print("float32 MB:", km32.nbytes / 1e6, "| biggest rounding error (km):", float(np.abs(km - km32).max()))
print("integers overflow silently:", np.array([120, 100], dtype=np.int8) + np.array([10, 100], dtype=np.int8))

# broadcasting: a (3 cities, 1) column against a (1, 4 vehicle) row makes a 3x4 table with no loop
base_fare = np.array([[40.0], [45.0], [50.0]])        # shape (3, 1): per city
per_km = np.array([[9.0, 11.5, 14.0, 18.0]])          # shape (1, 4): per vehicle type
price_for_10km = base_fare + per_km * 10               # shape (3, 4)
print("shapes:", base_fare.shape, "+", per_km.shape, "->", price_for_10km.shape)
print(price_for_10km)
what it printed
dtype: float64 | bytes per number: 8 | total MB: 8.0
loop 98.7 ms | vectorised 4.27 ms | speedup about 23x
same answer: True
float32 MB: 4.0 | biggest rounding error (km): 1.9067169461095546e-06
integers overflow silently: [-126  -56]
shapes: (3, 1) + (1, 4) -> (3, 4)
[[130. 155. 180. 220.]
 [135. 160. 185. 225.]
 [140. 165. 190. 230.]]

Read the output. The array uses exactly 8.0 MB, which is 1,000,000 numbers at 8 bytes each. The loop took 98.7 milliseconds and the array expression 4.27, about 23 times faster. Your numbers will differ because the timing depends on your machine. The line "same answer: True" matters most: speed is only useful if the result is unchanged.

One million trip fares: 40 + 11.5 x km Python loop 98.7 ms 1 NumPy array 4.27 ms 2 the loop takes about 23 times as long 3 same answer: allclose = True
Fig. 2.1 — The same arithmetic on one million numbers: the loop is the long red bar, the array is the sliver beside it.
  1. The loop. Python visits each of the 1,000,000 numbers one at a time, checks what kind of object it is, multiplies, adds, and stores a new object. That bookkeeping, not the arithmetic, is the 98.7 milliseconds.
  2. The array. NumPy keeps the numbers side by side in one block of memory and runs one compiled loop over them. It took 4.27 milliseconds on this machine.
  3. The ratio. About 23 times faster here. The exact ratio changes with your computer and the size of the data, so treat it as a rough size, not a promise. The two answers agree, so nothing was lost.

The honest caveat: at one million simple sums a loop costs a tenth of a second, which nobody notices. The gap matters when the work repeats, such as simulating thousands of times, or when the arithmetic is heavier. The lasting benefit is that you write one clear line instead of four.

dtypes: the size of the box

Priya's file will soon hold fares and distances as numbers. Before she trusts any total, she needs to know what box each number sits in. A box that is too small does not complain. It quietly gives the wrong answer.

A dtype (data type) is the kind and size of the box every number in the array lives in. The default decimal box, float64, is 8 bytes. The program above also made a float32 copy at half the memory, with a worst-case rounding error of 0.0000019 km. That is harmless for distances.

float64 8 bytes each 1,000,000 numbers = 8.0 MB 1 float32 4 bytes each same numbers = 4.0 MB largest error 0.0000019 km 2 int8 1 byte: -128 to 127 120 + 10 -> -126 100 + 100 -> -56 3 Smaller boxes save memory. A number that does not fit wraps around, with no warning.
Fig. 2.3 — A dtype is the size and kind of the box each number lives in; a box that is too small gives wrong answers, not errors.
  1. float64, the default. Eight bytes per number, about 15 to 16 correct digits. One million trip distances take 8.0 MB.
  2. float32. Half the memory, about 7 correct digits. For kilometres the worst error on these 1,000,000 values was 0.0000019 km, which is harmless. This is why deep-learning code (module 04) uses it.
  3. int8. A whole number stored in one byte can only hold -128 to 127. 120 + 10 does not fit, so it wraps to -126. NumPy gives no warning for array arithmetic, which is why dtype is the first thing to check when a total looks absurd.

The dangerous direction is whole-number boxes that are too small. In marker 3 in Fig. 2.3, 120 + 10 in an int8 array gives -126. Nothing raised an error. When a total looks absurd, check the dtype first.

Broadcasting: a column meets a row

Marcus's question will soon need a grid: cancel rate by weekday and by hour. That is a table whose rows come from one list and whose columns come from another. NumPy's name for building such a table without loops is broadcasting.

Broadcasting is the rule that lets arrays of different shapes be combined. When one array has size 1 in a direction, NumPy repeats it along that direction to match the other. Here is the smallest case, with prices for three cities and four vehicle types.

per_km * 10 shape (1, 4) 90 115 140 180 2 base_fare shape (3, 1) 40 45 50 1 130 155 180 220 135 160 185 225 140 165 190 230 3 result shape (3, 4) = 12 sums, no loop written 4 highlighted: city 2, vehicle 3 -> 45 + 140 = 185
Fig. 2.2 — Broadcasting stretches a size-1 direction to match the other array, so a (3,1) column plus a (1,4) row gives a (3,4) table.
  1. The column. Three base fares, 40, 45 and 50 rupees, one per city. Its shape is (3, 1): three rows, one column. Each dashed arrow copies that fare across all four columns.
  2. The row. Four prices per kilometre multiplied by 10 km: 90, 115, 140 and 180. Its shape is (1, 4). Each dashed arrow copies the value down all three rows.
  3. One result cell. Row 2, column 3 is 45 (from the column) plus 140 (from the row) = 185. Every one of the 12 cells is built this way.
  4. The shape rule. Line the shapes up from the right. Each pair of sizes must be equal, or one of them must be 1. (3,1) with (1,4) passes, and the result takes the larger size in each place.

Read Fig. 2.2 like this. The column on the left, marker 1, is copied rightwards. The row on top, marker 2, is copied downwards. The highlighted cell, marker 3, is 45 plus 140 = 185.

🧠 Brain power

Before reading on: what happens if you try to add a shape (3,) array to a shape (4,) array? Work it out from the shape rule in marker 4 in Fig. 2.2.

Reveal the answer

NumPy raises a ValueError: shapes (3,) and (4,) cannot be broadcast. Lined up from the right, 3 and 4 are different and neither is 1. Raising an error here is the helpful behaviour: it is a bug in your thinking, caught early. The mistake that does not raise an error is a (3,) added to a (3,1), which silently makes a 3-by-3 table.

"Python lists and a for loop are fine. Why learn another way to add numbers?"

— a nine-year engineer, right about now

For one hundred numbers you are right, and the loop is clearer. The array way wins on three counts: 23 times faster at a million numbers in Fig. 2.1, one line instead of four, and every data library from pandas to PyTorch speaks arrays, so the idea transfers.

The honest downside: arrays are fixed in size and type. Appending one element means building a new array. A list is still the right tool for small, mixed, changing collections.

Say it to the whole array, not the elements.

Check the shape before you add.

Check the dtype before you trust a total.

Line 1 is the loop-versus-array gap in Fig. 2.1. Line 2 is the shape rule under marker 4 in Fig. 2.2. Line 3 is the int8 wrap-around at marker 3 in Fig. 2.3.

Quick reference — NumPy

ndarray
A fixed-size block of numbers that all share one dtype.
Vectorised
One operation applied to every element inside compiled code, with no Python loop. About 23 times faster on one million sums here.
dtype
The box size and kind: float64 is 8 bytes, float32 is 4, int8 is 1 and holds only -128 to 127.
shape
The array's size in each direction, such as (3, 4). Check it before every operation.
Boolean mask
km[km > 6] keeps the elements where the test is True.
Broadcasting
Line shapes up from the right; each pair of sizes must be equal or one must be 1. Size-1 directions are stretched.
Why it matters later
pandas columns are arrays underneath, and PyTorch tensors in module 04 follow the same shape and dtype rules.

03 · pandas 3Tables: Rows, Columns and the Questions You Ask Them

Tuesday morning. Priya understands arrays now, and she has opened trips_raw.csv for the first time. It has 50,000 rows and twelve columns, some of them numbers and some of them text pretending to be numbers. She needs a table object that can hold both kinds of column and answer "how many, per what?" in one line. That object is a pandas DataFrame.

pandas is a library for tables: named columns, labelled rows, and one-line operations to filter, group, join and summarise them. Without it you would write the same loops over rows by hand, one more bug at a time.

Start with six trips

Fifty thousand rows is too many to see. So the first program uses six trips small enough to read at a glance. Everything it does, a DataFrame does the same way to 50,000 rows. As of October 2026 the course environment has pandas 3.0, and the program prints its own version to prove it.

index trip_id city fare_inr status 0 T1 Pune 120.0 completed 1 T2 Hyderabad 340.0 cancelled_rider 2 T3 Pune 95.0 cancelled_rider 3 T4 Mumbai NaN completed 4 T5 Hyderabad 410.0 completed 5 T6 Pune 150.0 completed 1 2 3 4 loc: label or test fare_inr > 200: T2, T5 iloc: by position rows 0-1 of column 1: Pune, Hyderabad 6 rows x 4 columns
Fig. 3.1 — A DataFrame is a table with a labelled row index and named columns; every column on its own is a Series.
  1. The index. The row labels 0 to 5 down the left. loc looks rows up by these labels. They are labels first and positions only by coincidence, which matters after rows are filtered or sorted.
  2. A column is a Series. The accent column, fare_inr, is one Series: a labelled, typed run of values. trips['fare_inr'] returns it. Its missing value, NaN for T4, is how pandas writes 'no number here'.
  3. loc. trips.loc[trips['fare_inr'] > 200, ['trip_id', 'fare_inr']] keeps the two green rows, T2 and T5, and only the two named columns.
  4. iloc. trips.iloc[0:2, 1] means the first two rows of the second column, counted by position from 0. The end of an iloc range is excluded, so 0:2 gives two rows.

Fig. 3.1 is the table the program builds. The row labels down the left are the index (marker 1). Each column, such as fare_inr (marker 2), is a Series: one labelled, typed list of values. The whole table is a DataFrame.

Step-by-step: what pandas_basics.py does, in plain English
  1. It builds a six-row DataFrame from a dictionary of columns, and a small three-row drivers table.
  2. It prints the pandas version and the dtype of the city column. In pandas 3 text columns have the dtype str.
  3. trips.loc[condition, columns] keeps rows where the fare is above 200 and only two named columns. loc works by label and by true-or-false condition.
  4. trips.iloc[0:2, 1] picks by position: the first two rows of the second column. iloc never looks at labels.
  5. It takes the fare column as a separate variable, edits its first value, then prints the original table's value, to show that copy-on-write protects the original.
  6. isna().sum() counts missing values per column. mean() shows that averages skip them.
  7. groupby("city").agg(...) makes one summary row per city.
  8. merge(..., how="left") attaches each trip's driver rating by driver_id.
  9. pivot_table counts trips by city (down) and status (across).
pandas_basics.pyruns offline
# pandas_basics.py -- the pandas 3 vocabulary on six RideNow trips small enough to see.
# pip install "pandas>=3,<4" "pyarrow>=20"
import pandas as pd

trips = pd.DataFrame({
    "trip_id": ["T1", "T2", "T3", "T4", "T5", "T6"],
    "city": ["Pune", "Hyderabad", "Pune", "Mumbai", "Hyderabad", "Pune"],
    "driver_id": ["D1", "D2", None, "D3", "D2", "D1"],
    "fare_inr": [120.0, 340.0, 95.0, None, 410.0, 150.0],
    "status": ["completed", "cancelled_rider", "cancelled_rider", "completed", "completed", "completed"],
})
drivers = pd.DataFrame({"driver_id": ["D1", "D2", "D3"], "rating": [4.8, 4.1, 4.6]})

print("pandas", pd.__version__, "| text column dtype:", trips["city"].dtype)       # 'str' in pandas 3

# loc picks by label and condition; iloc picks by position
print(trips.loc[trips["fare_inr"] > 200, ["trip_id", "fare_inr"]].to_dict("records"))
print(trips.iloc[0:2, 1])

# copy-on-write (always on in pandas 3): editing a slice never edits the table it came from
view = trips["fare_inr"]
view.iloc[0] = 999.0
print("original fare after editing the slice:", trips.loc[0, "fare_inr"])

# missing values are NaN / <NA>; counts and means skip them
print("missing per column:", trips.isna().sum().to_dict())
print("mean fare ignores the gap:", trips["fare_inr"].mean())

# groupby + agg: one row per city
print(trips.groupby("city").agg(trips=("trip_id", "size"), mean_fare=("fare_inr", "mean")))

# merge: attach driver ratings; how="left" keeps trips with no driver
print(trips.merge(drivers, on="driver_id", how="left")[["trip_id", "driver_id", "rating"]])

# pivot: cities down the side, statuses across the top
print(trips.pivot_table(index="city", columns="status", values="trip_id", aggfunc="count", fill_value=0))
what it printed
pandas 3.0.5 | text column dtype: str
[{'trip_id': 'T2', 'fare_inr': 340.0}, {'trip_id': 'T5', 'fare_inr': 410.0}]
0         Pune
1    Hyderabad
Name: city, dtype: str
original fare after editing the slice: 120.0
missing per column: {'trip_id': 0, 'city': 0, 'driver_id': 1, 'fare_inr': 1, 'status': 0}
mean fare ignores the gap: 223.0
           trips   mean_fare
city                        
Hyderabad      2  375.000000
Mumbai         1         NaN
Pune           3  121.666667
  trip_id driver_id  rating
0      T1        D1     4.8
1      T2        D2     4.1
2      T3       NaN     NaN
3      T4        D3     4.6
4      T5        D2     4.1
5      T6        D1     4.8
status     cancelled_rider  completed
city                                 
Hyderabad                1          1
Mumbai                   0          1
Pune                     1          2

Read the output. The first line confirms pandas 3.0.5 and the text dtype str. The loc line returns the two expensive trips, T2 and T5. The edit-a-slice line prints 120.0, the original value, so the change never reached the table. The missing-value line shows one gap in driver_id and one in fare_inr. The mean is 223.0, which is 1,115 divided by the five fares that exist.

What changed in pandas 3

If you learned pandas before 2026, three defaults are different. Each one removes a trap you may remember.

These facts come from the pandas 3.0 release notes (released 21 January 2026) and from running the program above. Code written for pandas 2.x that relied on edit-through-a-view will now do nothing silently, so upgrade with the 2.3 deprecation warnings cleared first.

groupby: split, apply, combine

Priya's first real question is "what share of trips is cancelled, per city?" That is a groupby. It is the single most used pandas operation in this chapter, so she walks through it on the six trips before trusting it on 50,000.

trips T1 Pune 120 T2 Hyderabad 340 T3 Pune 95 T4 Mumbai NaN T5 Hyderabad 410 T6 Pune 150 1 split 1 Pune 120, 95, 150 Hyderabad 340, 410 Mumbai NaN 2 apply: size, mean 2 result (one row per city) Pune 3 121.67 Hyderabad 2 375.0 Mumbai 1 NaN 3 combine 3 trips mean_fare
Fig. 3.2 — groupby is split, apply, combine: the six rows are sorted into one bundle per city, each bundle is summarised, and the summaries become the result table.
  1. Split. pandas reads the city column and puts each row into the bundle with its city name: three Pune rows, two Hyderabad rows, one Mumbai row. Nothing is calculated yet.
  2. Apply. Each bundle gets the same summaries. size counts rows. mean averages the fares and skips NaN: Pune is (120 + 95 + 150) / 3 = 121.67, Hyderabad is (340 + 410) / 2 = 375.0.
  3. Combine. One row per bundle comes back as a new table. Mumbai's only fare is missing, so its mean is NaN, not 0. That is honest: an average of nothing is unknown.

Fig. 3.2 has three moves. The split (marker 1) sorts rows into bundles. The apply (marker 2) summarises each bundle. The combine (marker 3) stacks the summaries into a new table.

Anatomy of a groupby summary — the one line to know by heart
by_city = trips.groupby("city"1).agg(2
    trips=("trip_id", "size"3),
    mean_fare=("fare_inr", "mean"4),
)
  1. The grouping column. Rows with the same value in this column go into one bundle. Pass a list to group by two columns. Mistake: forgetting that rows whose key is missing are dropped from the groups by default.
  2. .agg(...) with named results. Each keyword on the left is the name of an output column. This "named aggregation" form gives clear column names. Mistake: using the old dictionary form, which produces nested column labels you must then flatten.
  3. A column and "size". size counts rows in the bundle, including rows with missing values. Mistake: confusing it with count, which counts only the non-missing values.
  4. A column and "mean". Averages the non-missing values in each bundle. A bundle with nothing to average gives NaN, not 0.

"Everyone says Polars is faster. Why teach pandas?"

— the engineer who reads Hacker News

Polars is fast, and its query style is tidy. But almost every tutorial, library and colleague's notebook you will meet in AI work speaks pandas, and scikit-learn, seaborn and most model-serving code take pandas frames directly. pandas 3 also closed some of the old gaps with Arrow-backed text and copy-on-write.

The honest downside: pandas runs on one CPU core and holds the whole table in memory. For files of tens of millions of rows, the stack table later in this chapter says when to switch.

Questions you might be asking now

The figures above packed a lot into a few lines. If one did not land, open the question that matches yours. Every answer uses the same six trips, small enough to check with a pencil.

The six trips every answer below uses (the same table as Fig. 3.1)
Row labeltrip_idcitydriver_idfare_inrstatus
0T1PuneD1120.0completed
1T2HyderabadD2340.0cancelled_rider
2T3Pune(none)95.0cancelled_rider
3T4MumbaiD3NaNcompleted
4T5HyderabadD2410.0completed
5T6PuneD1150.0completed
What is the difference between loc and iloc? They look the same.

loc finds rows by their label. iloc finds rows by their position, counting from 0. On a fresh table the two agree. After you filter, they do not, and that is where people get hurt.

Keep only the completed trips, then ask both for "row 3". The program followups_pandas.py prints the result.

  1. Filter. Completed trips are T1, T4, T5 and T6. They keep their original labels, so the kept labels are 0, 3, 4, 5.
  2. done.loc[3]. "Find the row labelled 3." That is T4.
  3. done.iloc[3]. "Take the fourth row, counting from 0: positions 0, 1, 2, 3." The kept rows in order are T1, T4, T5, T6, so position 3 is T6.
Same request, two meanings
loc[3]iloc[3]
Looks atthe label 3the fourth row
Answer on the filtered tableT4T6
Slice endincludedexcluded

The honest limit: if you never filter or sort, you will never see them disagree. That is exactly why the bug survives code review.

Use loc when you mean "this label or this condition" and iloc when you mean "the n-th row", and never mix up the two after filtering.

What does groupby actually do, step by step? Where is the loop?

It sorts the rows into bundles by the key column, runs the same summary on each bundle, and stacks the results. The loop exists but runs inside pandas, so you write one line.

  1. Find the keys. The city column has three distinct values: Hyderabad, Mumbai, Pune.
  2. Build bundles. Pune gets fares 120, 95, 150. Hyderabad gets 340, 410. Mumbai gets NaN.
  3. Pune's mean. (120 + 95 + 150) ÷ 3 = 365 ÷ 3 = 121.67.
  4. Hyderabad's mean. (340 + 410) ÷ 2 = 750 ÷ 2 = 375.0.
  5. Mumbai's mean. There is nothing to average after skipping the missing value, so the answer is NaN.

You can verify this: the program prints each bundle's list and mean, and they match the lettered steps. The same moves are drawn in Fig. 3.2.

groupby is "sort into bundles, summarise each bundle, stack the answers", and a bundle with no usable values gives NaN, not zero.

What is the difference between a left merge and an inner merge?

Both attach driver ratings to trips by driver_id. A left merge keeps every trip, even without a match. An inner merge keeps only trips that found a driver. On our six trips: six rows against five.

trips drivers after merge T1 D1 T1 4.8 T2 D2 T2 4.1 T3 None T3 NaN T4 D3 T4 4.6 T5 D2 T5 4.1 T6 D1 T6 4.8 D1 4.8 D2 4.1 D3 4.6 T3 has no line: nothing to look up how='left' 1 2 3
Fig. 3.3 — merge is a lookup: each trip row finds the driver row with the same driver_id, and a left merge keeps the trip even when no driver matches.
  1. The left table. Six trips with the key driver_id. T3 has no driver id at all (a rider cancelled before a match).
  2. The right table. One row per driver, with the rating. The merge looks each trip's id up in this table.
  3. The result. Still six rows, because how='left' keeps every trip. T3 finds nothing to attach, so its rating is NaN. how='inner' would have dropped T3 and returned five rows.
  1. Look up each trip's driver. T1 and T6 find D1 (4.8). T2 and T5 find D2 (4.1). T4 finds D3 (4.6).
  2. T3 finds nothing. Its driver_id is missing: a rider cancelled before anyone was matched.
  3. Left merge. Keeps T3 with a rating of NaN. Six rows.
  4. Inner merge. Drops T3. Five rows. The program prints "left rows: 6 | inner rows: 5 | trip lost by inner: ['T3']".

The honest limit: dropping T3 silently is exactly how a cancellation analysis loses its most interesting rows. In this chapter, T3's kind of row is 55% of rider cancellations.

Use how="left" when the left table is the thing you are counting, and check the row count before and after every merge.

What is NaN, and why doesn't pandas just treat a missing fare as 0?

NaN means "not a number", which is how pandas writes "this value is unknown". Treating unknown as 0 would invent a free trip and drag every average down.

  1. Five fares exist. 120 + 340 + 95 + 410 + 150 = 1,115.
  2. Skip the gap. The mean is 1,115 ÷ 5 = 223.0. This is what pandas prints by default.
  3. Pretend the gap is 0. The mean would be 1,115 ÷ 6 = 185.83. The program prints that too.
  4. The difference. 223.0 against 185.83 is a drop of 37 rupees, caused by one number nobody knows.

The honest limit: skipping NaN is also an assumption, namely that the missing trip is like the others. Later you will see a case where that is false.

Missing means unknown, so leave it unknown until you have decided on purpose how to treat it.

Quick reference — pandas 3

Series, DataFrame
A labelled, typed column; a table of such columns sharing one row index.
loc / iloc
loc selects by label or true-or-false condition. iloc selects by position, end excluded.
str dtype
The default text type in pandas 3, Arrow-backed when pyarrow is installed.
Copy-on-write
Always on in pandas 3: editing a slice never edits its parent. Verified by the 120.0 line.
groupby + agg
Split rows into bundles, summarise each, combine. Named aggregation gives clean column names.
merge
A lookup by key. left keeps all left rows; inner keeps only matches. Check row counts.
NaN
Unknown, not zero. Sums and means skip it; counts of rows (size) include it.
pivot_table
Cities down, statuses across, counts in the cells.

04 · Cleaning the exportA Checklist, Not a Mood

Tuesday afternoon. Priya can build a table and group it. She runs her first question straight on the raw file, "average distance per trip", and gets 19.8 km in a city where nobody rides that far. Something in the file is lying. Before any finding, she needs a repeatable way to find every lie and say how many there were.

Cleaning means making every column have one type, one unit and one meaning, and writing down what you changed. Without it, the first average you compute is wrong in a way nobody notices.

Her checklist has five steps, in this order. The order matters, because each step makes the next one possible. You cannot find duplicates until the timestamps agree, and you cannot judge a distance until it is a number.

  1. Types. Turn text into the type each column really is: timestamps, numbers, categories.
  2. Spellings. Make one meaning have one spelling: five cities, not twenty-one.
  3. Duplicates. Remove rows that describe the same event twice.
  4. Impossible values. Find numbers no real trip could have, and blank them without deleting the row.
  5. Missing values. Decide what each gap means, then choose to drop, fill or flag.

One timestamp first

The hardest column is the time, so it gets a tiny program before the real one. This one reads a single time written three ways and moves each to Indian time. Run it, then compare with Fig. 4.1.

Step-by-step: what tiny_datetime.py does, in plain English
  1. format="ISO8601", utc=True reads text like 2026-08-15T18:03:51Z. The trailing Z means UTC, so the result carries a time zone.
  2. tz_convert("Asia/Kolkata") changes the same moment to Indian clock time. The moment does not change, only how it is written.
  3. The day-first text 18/09/2026 22:43 has no zone, so format="%d/%m/%Y %H:%M" says which part is the day. tz_localize then says "this was Indian time". Without it pandas would not know.
  4. day_name() and hour read the weekday and hour off the moment.
  5. Seconds since 1970 become a time with unit="s", and are always UTC.
tiny_datetime.pyruns offline
# tiny_datetime.py -- one timestamp, read three ways, moved to Indian time.
# pip install "pandas>=3,<4"
import pandas as pd

utc_text = pd.to_datetime("2026-08-15T18:03:51Z", format="ISO8601", utc=True)
print(utc_text, "->", utc_text.tz_convert("Asia/Kolkata"))
day_first = pd.to_datetime("18/09/2026 22:43", format="%d/%m/%Y %H:%M").tz_localize("Asia/Kolkata")
print(day_first, "| day of week:", day_first.day_name(), "| hour:", day_first.hour)
print(pd.to_datetime(1788175947, unit="s", utc=True).tz_convert("Asia/Kolkata"))
what it printed
2026-08-15 18:03:51+00:00 -> 2026-08-15 23:33:51+05:30
2026-09-18 22:43:00+05:30 | day of week: Friday | hour: 22
2026-08-31 17:02:27+05:30

Read the output. The UTC time 18:03:51 became 23:33:51 in India, five and a half hours later, and the date stayed the 15th. The legacy text was a Friday at 22:43. The epoch number landed on 31 August at 17:02:27. Three formats, one clock, one comparable value each.

what the file says how it is read Indian time 2026-08-15T18:03:51Z UTC ISO text (27,452) 2026-08-15 23:33 2026-09-18 12:51:23+05:30 IST + offset (10,105) 2026-09-18 12:51 18/09/2026 22:43 day first, no zone (8,547) 2026-09-18 22:43 1788175947 epoch seconds (3,896) 2026-08-31 17:02 1 2 3 Zone thrown away: the busiest hour among the UTC rows looks like 14:00. Converted properly: the same trips peak at 19:00. Every trip moved 5.5 hours. 4
Fig. 4.1 — Four spellings of a time, each needing its own reading rule, all landing on one clock: Indian time.
  1. Four shapes in one column. The same column holds ISO text ending in Z, ISO text with +05:30, day-first dates with no zone, and bare seconds. The row counts add up to all 50,000.
  2. A rule per shape. Z means UTC. +05:30 carries its own offset. The legacy system wrote local Indian time without saying so, and we know that from its owner, not from the data. Seconds since 1970 are always UTC.
  3. One clock. Every row becomes an Indian-time moment. Two different trips written as '18/09/2026 22:43' and '2026-09-18 12:51:23+05:30' are now directly comparable.
  4. The cost of skipping it. Keep the digits of the UTC rows and drop the Z, and the busiest hour comes out as 14:00. Done right it is 19:00. Hour-of-day is the heart of our question, so this mistake would have wrecked the answer.

The picture shows all four formats in the real file, with their counts. Every rule in it came from asking where the data came from: the app writes UTC, the partner export writes India time with an offset, and the old system writes India time with no zone. Nothing in the file itself says that last part. You learn it by asking the people who own the system.

BE the timestamp parser

Play the machine. For each text below, decide which of the four rules applies and write the Indian clock time, with a pencil, before you open the answer.

  1. 2026-08-15T18:03:51Z
  2. 2026-09-18 12:51:23+05:30
  3. 18/09/2026 22:43
  4. 1788175947 (a bare number)

Which of the four needs outside knowledge, not just reading the text?

Check your answer

First: ends in Z, so UTC, and 5.5 hours later is 2026-08-15 23:33. Second: carries +05:30 already, so it is 12:51 India time, unchanged. Third: day-first with no zone, so 22:43 India time only because the legacy system's owner told us so. Fourth: seconds since 1970 are UTC, giving 2026-08-31 17:02 India time.

The third is the one that needs outside knowledge. Also notice that 03/08/2026 would be read as 8 March by a month-first parser, with no error at all. That is why the format is spelled out and not guessed.

Watch it break: the lazy parse

Failure mode

The lazy way is to hand the whole column to pd.to_datetime and hope. The program below tries that, then tries the second-laziest fix: throw the zone away and keep the clock digits. Both go wrong, and the second goes wrong quietly.

Step-by-step: what timezone_trap.py does, in plain English
  1. It reads the raw CSV with every column as text.
  2. Attempt 1: it asks pandas to guess the format of the whole column, and prints the error.
  3. Attempt 2: it takes only the rows ending in Z, strips the Z, and reads the digits as if they were already Indian time.
  4. It also converts those rows correctly, UTC to Indian time.
  5. It prints the busiest hour both ways and the size of the shift.
timezone_trap.pyruns offline
# timezone_trap.py -- what happens to the 'busy hour' if you parse mixed timestamps carelessly.
# pip install "pandas>=3,<4" "pyarrow>=20"      (needs data/trips_raw.csv)
from pathlib import Path

import pandas as pd

raw = pd.read_csv(Path(__file__).parent / "data" / "trips_raw.csv", dtype=str, keep_default_na=False)
ts = raw["requested_at"]

# attempt 1: let pandas guess the whole column
try:
    pd.to_datetime(ts, format="mixed")
except ValueError as err:
    print("pandas refuses:", str(err)[:60], "...")

# attempt 2: 'fix' it by throwing the zone away and keeping the clock digits
z = ts[ts.str.endswith("Z")]
digits_only = pd.to_datetime(z.str.rstrip("Z"), format="ISO8601")           # UTC digits read as if they were local
correct = pd.to_datetime(z, format="ISO8601", utc=True).dt.tz_convert("Asia/Kolkata")
print("rows written in UTC:", len(z), "of", len(ts))
busy_wrong = digits_only.dt.hour.value_counts().idxmax()
busy_right = correct.dt.hour.value_counts().idxmax()
print("busiest hour, zone thrown away:", busy_wrong, "| in Indian time:", busy_right)
gap = correct.dt.tz_localize(None) - digits_only
shift = gap.dt.total_seconds().div(3600).unique()
print("every one of those trips moved by", shift.tolist(), "hours")
what it printed
pandas refuses: year 1788175947 is out of range: 1788175947 ...
rows written in UTC: 27452 of 50000
busiest hour, zone thrown away: 14 | in Indian time: 19
every one of those trips moved by [5.5] hours

Read the output. Attempt 1 fails loudly: the epoch numbers cannot be read as a year, which is the good kind of failure. Attempt 2 runs without complaint and says the busiest hour is 14:00. The correct answer is 19:00. Every UTC trip moved by exactly 5.5 hours. Since the question is about which hours go wrong, this single mistake would have pointed Priya at the wrong part of the day.

Fireside chat

Tonight's talk: "Drop the row" and "Fill the gap" argue over who handles missing data better.

Drop the row
Fill the gap

I am honest. If a fare is missing, I remove the trip, and nothing in the table is made up. Fifty-five percent of rider cancellations have no driver id, and I just say so by leaving those out.

Dropping rows never invents data, but look at the 55%: dropping them removes most of the rider cancellations, which is the thing Priya is studying.

You are honest and you are blind. Those rows are not random damage. A rider cancelled before a driver was matched. If you delete them, the cancel rate you report is lower than the truth. I would at least keep the row and put something sensible in the missing cell.

The missing driver id means something: nobody had been matched. Deleting it hides a real group of trips.

And what do you put in the cell? A driver id that does not exist? You fill pickup waits with the city median and then your averages look calmer than the real data, because you added 4% of rows that all sit exactly in the middle.

Filling with a typical value shrinks the spread of the data. A fill is a guess, and every number built on it inherits the guess.

Fair. So I fill only when a gap is small and random, I say how many I filled, and I mark each one with a flag column. Then a later step can ignore them.

A fill is acceptable when the gap is small and random, when you count it and when you flag it. The flag lets you undo the choice later.

Then we agree you need a flag, and I need a count of what I removed. We will revisit which of us wins when the missing share gets large.

Both need a count and a flag. Neither is right by default; the table below says when each fits.

Decision table: what to do with a missing or impossible value
ChoiceChoose whenAvoid whenRideNow example
Drop the rowThe row is useless without the value and few rows are affected (under about 1%)The gap is common or tied to the outcome you studyNone here; we never drop trips for a missing value
Blank the value, keep the rowThe value is impossible but the rest of the row is fineYou cannot tell which value was wrong457 fares of 0 or less; 295 distances of 0 or over 150 km
Fill with a typical value (plus a flag)The gap is small, random and the column is a numberThe gap is large, or you will analyse the spread of that columnPickup wait missing on about 4% of rows, filled with the city median
Keep the gap as a flag columnThe gap itself carries meaningNever fill a meaningful gap with a made-up idno_driver: rider cancelled before a match
Leave it unknownFilling would be a guess and the analysis can skip those rowsThe skipped rows are a different kind from the kept onesSurge multiplier unreadable on 493 rows

Now build the whole pipeline, in five chunks

Priya has seen every cleaning move on a small scale. Now she writes it down as one program, so that anyone, including Priya next quarter, can rerun the cleaning on a fresh export. The program is about eighty lines, which is too much to read at once. So it is built in five chunks, and each one runs on its own.

Build it in chunks

We build clean_trips.py in five chunks. Each one runs on its own and prints what it found. The whole file comes at the end. Run generate_trips.py once first to make the raw data.

  1. Chunk 1 — load the file as text and change nothing

    We start by refusing to let pandas guess. Reading every column as text means a number-shaped mistake cannot be hidden by a wrong guess. Nothing is lost, and the next chunks decide each type on purpose.

    Step-by-step: what chunk 1 does, in plain English
    1. Import Path and pandas, and work out where the data folder is relative to the script.
    2. dtype=str keeps every column as text. keep_default_na=False stops pandas turning an empty cell into NaN so early that we cannot tell blanks from missing.
    3. Read the drivers table normally; it is small and clean.
    4. Print the row count and that every column is text.
    clean_trips.py — chunk 1runs offline
    # clean_trips.py -- turn RideNow's messy export into a table you can trust.
    # pip install "pandas>=3,<4" "pyarrow>=20"      (run generate_trips.py once first)
    from pathlib import Path
    
    import pandas as pd
    
    HERE = Path(__file__).parent
    DATA = HERE / "data"
    
    # ── chunk 1: load everything as text, change nothing yet ──
    # dtype=str: we decide every type ourselves, so pandas cannot guess wrong silently.
    raw = pd.read_csv(DATA / "trips_raw.csv", dtype=str, keep_default_na=False)
    drivers = pd.read_csv(DATA / "drivers.csv")
    print(f"loaded {len(raw):,} rows x {raw.shape[1]} columns; every column is {raw['city'].dtype}")
    

    read_csv(dtype=str) — load everything as text, decide types later.

    Run python3 clean_trips.py. You should see:

    what it printed
    loaded 50,000 rows x 12 columns; every column is str
    
  2. Chunk 2 — one clock for all timestamps

    Time is the column everything else depends on, and the one where mistakes are silent, so it comes before the others. This chunk uses the four rules from Fig. 4.1.

    Step-by-step: what chunk 2 does, in plain English
    1. Classify every timestamp by its shape: ends in Z, ends in +05:30, contains a slash, or is all digits.
    2. assert ... .all() stops the program if any row fits none of the four shapes, so a fifth format cannot slip through.
    3. Make an empty column of UTC times to fill in group by group.
    4. The two ISO groups are parsed together with format="ISO8601".
    5. The legacy group is parsed with an explicit day-first format, labelled as Indian time, then converted to UTC.
    6. The epoch group is converted with unit="s".
    7. The finished column is converted to Indian time and replaces the old text column. Print the counts and the date range.
    clean_trips.py — chunk 2runs offline
    # ── chunk 2: one clock for all timestamps ──
    # Three source systems wrote three formats. Look at the shape of the text, then parse each shape on its own.
    ts = raw["requested_at"]
    is_utc_iso = ts.str.endswith("Z")
    is_ist_iso = ts.str.endswith("+05:30")
    is_legacy = ts.str.contains("/", regex=False)
    is_epoch = ts.str.fullmatch(r"\d+")
    assert (is_utc_iso | is_ist_iso | is_legacy | is_epoch).all(), "a timestamp shape we have not seen"
    
    parsed = pd.Series(pd.NaT, index=raw.index, dtype="datetime64[ns, UTC]")
    iso = is_utc_iso | is_ist_iso
    parsed[iso] = pd.to_datetime(ts[iso], format="ISO8601", utc=True)
    # legacy rows carry no zone: the old system ran on Indian time, so we say so out loud.
    legacy_local = pd.to_datetime(ts[is_legacy], format="%d/%m/%Y %H:%M").dt.tz_localize("Asia/Kolkata")
    parsed[is_legacy] = legacy_local.dt.tz_convert("UTC")
    parsed[is_epoch] = pd.to_datetime(ts[is_epoch].astype("int64"), unit="s", utc=True)
    raw["requested_at"] = parsed.dt.tz_convert("Asia/Kolkata")     # report in the city's own clock
    print("formats seen:", {"utc_iso": int(is_utc_iso.sum()), "ist_iso": int(is_ist_iso.sum()),
                             "legacy": int(is_legacy.sum()), "epoch": int(is_epoch.sum())})
    print("span:", raw["requested_at"].min().strftime("%Y-%m-%d %H:%M"), "to", raw["requested_at"].max().strftime("%Y-%m-%d %H:%M"))
    

    .str.endswith, boolean masks as row selectors, and tz_localize followed by tz_convert.

    Run it again. Two new lines appear:

    what it printed
    formats seen: {'utc_iso': 27452, 'ist_iso': 10105, 'legacy': 8547, 'epoch': 3896}
    span: 2026-08-03 00:00 to 2026-09-27 23:59
    
  3. Chunk 3 — fix spellings and number-shaped text

    With the clock fixed, we fix the labels. Hyderabad alone has six spellings, so a groupby on the raw column would have split its trips into six small groups.

    Step-by-step: what chunk 3 does, in plain English
    1. A dictionary maps every lower-case spelling to its one proper name.
    2. Remember how many distinct spellings there were.
    3. Trim spaces, lower-case, then .map() through the dictionary. A spelling not in the dictionary becomes NaN.
    4. assert ... notna().all() stops the program if any spelling is missing from the dictionary.
    5. Lower-case the status, because some rows say "Completed".
    6. Surge text like 1.5x loses its x and becomes a number. errors="coerce" turns anything unreadable into NaN instead of crashing.
    7. The other three number columns are converted the same way. Empty driver ids become a real missing value.
    clean_trips.py — chunk 3runs offline
    # ── chunk 3: spellings and number-shaped text ──
    city_map = {
        "bengaluru": "Bengaluru", "bangalore": "Bengaluru", "blr": "Bengaluru",
        "hyderabad": "Hyderabad", "hyd": "Hyderabad", "hyd.": "Hyderabad", "hydrabad": "Hyderabad",
        "mumbai": "Mumbai", "bombay": "Mumbai", "mum": "Mumbai",
        "pune": "Pune", "chennai": "Chennai", "madras": "Chennai",
    }
    before = raw["city"].nunique()
    raw["city"] = raw["city"].str.strip().str.lower().map(city_map)
    assert raw["city"].notna().all(), "a spelling is missing from city_map"
    raw["status"] = raw["status"].str.lower()
    raw["surge_multiplier"] = pd.to_numeric(raw["surge_multiplier"].str.rstrip("x"), errors="coerce")
    for col in ["distance_km", "pickup_eta_min", "fare_inr"]:
        raw[col] = pd.to_numeric(raw[col], errors="coerce")
    raw["driver_id"] = raw["driver_id"].replace("", pd.NA)
    print(f"city spellings {before} -> {raw['city'].nunique()}:", raw["city"].value_counts().to_dict())
    

    Series.map(dict), pd.to_numeric(errors="coerce") and assert as a safety net.

    One new line shows 21 spellings became 5:

    what it printed
    city spellings 21 -> 5: {'Bengaluru': 15004, 'Hyderabad': 12062, 'Mumbai': 11075, 'Chennai': 5971, 'Pune': 5888}
    
  4. Chunk 4 — remove duplicates and blank the impossible

    Duplicates come after parsing because two copies of one trip can differ only in how their time was written. Impossible values come next, and we blank them without deleting the row, because the rest of the row is still true.

    Step-by-step: what chunk 4 does, in plain English
    1. Remember the row count and count rows identical in every column.
    2. drop_duplicates(subset="trip_id") keeps the first row per trip id. This also catches copies whose timestamp text differed.
    3. Print how many were removed, split into the exact repeats and the others.
    4. Make two True/False flag columns: a fare of 0 or below, and a distance of 0 or below, or above 150 km.
    5. Blank those values with .loc[mask, column] = pd.NA, keeping the flags.
    6. Print how many of each were blanked.
    clean_trips.py — chunk 4runs offline
    # ── chunk 4: duplicates and impossible values ──
    n_before = len(raw)
    exact = int(raw.duplicated(keep="first").sum())            # identical in every column
    raw = raw.drop_duplicates(subset="trip_id", keep="first")   # same trip, any spelling of the timestamp
    print(f"duplicates: {exact} exact + {n_before - len(raw) - exact} same trip_id with a different timestamp text -> {len(raw):,} rows left")
    
    raw["bad_fare"] = raw["fare_inr"].le(0)
    raw["bad_distance"] = raw["distance_km"].le(0) | raw["distance_km"].gt(150)
    raw.loc[raw["bad_fare"], "fare_inr"] = pd.NA            # keep the row, blank the lie, remember we did
    raw.loc[raw["bad_distance"], "distance_km"] = pd.NA
    print(f"impossible: {int(raw['bad_fare'].sum())} fares <= 0, {int(raw['bad_distance'].sum())} distances <= 0 or > 150 km")
    

    duplicated, drop_duplicates(subset=...) and assigning to a masked selection with .loc.

    Two new lines. The row count is now exactly 49,000:

    what it printed
    duplicates: 958 exact + 42 same trip_id with a different timestamp text -> 49,000 rows left
    impossible: 457 fares <= 0, 295 distances <= 0 or > 150 km
    
  5. Chunk 5 — decide the missing values, join the drivers, save

    Last come the gaps and the join. The driver table adds each trip's driver rating and tenure, which finding 4 needs. The result is saved as Parquet so the next chapters and the analysis script load it with every type intact.

    Step-by-step: what chunk 5 does, in plain English
    1. Print the share of missing driver ids by trip status. This is the evidence that the gaps are meaningful.
    2. Add no_driver, a flag column, instead of filling the gap.
    3. Remember which pickup waits were missing, then fill them with the median of the same city, using groupby().transform("median").
    4. Flag unreadable surge values but leave them unknown.
    5. Left-merge the driver ratings and join dates onto the trips.
    6. Compute tenure: trip date minus join date, in days. Drop the helper column.
    7. Save to trips_clean.parquet and print the row count and the column types.
    clean_trips.py — chunk 5runs offline
    # ── chunk 5: missing values, the driver table, and a saved result ──
    print("missing driver_id by status:", raw.groupby("status")["driver_id"].apply(lambda s: round(s.isna().mean(), 3)).to_dict())
    raw["no_driver"] = raw["driver_id"].isna()                  # the gap itself is information: keep it as a column
    raw["eta_missing"] = raw["pickup_eta_min"].isna()
    raw["pickup_eta_min"] = raw["pickup_eta_min"].fillna(raw.groupby("city")["pickup_eta_min"].transform("median"))
    raw["surge_missing"] = raw["surge_multiplier"].isna()       # not guessed: analyses skip these rows
    
    trips = raw.merge(drivers[["driver_id", "joined_on", "rating"]], on="driver_id", how="left")
    trips["driver_tenure_days"] = (trips["requested_at"].dt.tz_localize(None).dt.normalize()
                                   - pd.to_datetime(trips["joined_on"])).dt.days
    trips = trips.drop(columns=["joined_on"])
    trips.to_parquet(DATA / "trips_clean.parquet", index=False)
    print(f"saved {len(trips):,} rows to data/trips_clean.parquet; dtypes:", dict(trips.dtypes.astype(str).value_counts()))
    

    groupby().transform (a group summary placed back on every row), merge(how="left") and to_parquet.

    Two new lines. The first shows the 55% pattern; the second confirms the save:

    what it printed
    missing driver_id by status: {'cancelled_driver': 0.005, 'cancelled_rider': 0.55, 'completed': 0.008}
    saved 49,000 rows to data/trips_clean.parquet; dtypes: {'str': np.int64(7), 'float64': np.int64(6), 'bool': np.int64(5), 'datetime64[ns, Asia/Kolkata]': np.int64(1)}
    

The whole program

Lines 1–15 are the imports and chunk 1, 16–36 chunk 2, 37–53 chunk 3, 54–65 chunk 4, 66–78 chunk 5. Every chunk starts with a # ── chunk n ── comment. This is the file saved as code/01c-python-for-data/clean_trips.py.

clean_trips.pyruns offline
# clean_trips.py -- turn RideNow's messy export into a table you can trust.
# pip install "pandas>=3,<4" "pyarrow>=20"      (run generate_trips.py once first)
from pathlib import Path

import pandas as pd

HERE = Path(__file__).parent
DATA = HERE / "data"

# ── chunk 1: load everything as text, change nothing yet ──
# dtype=str: we decide every type ourselves, so pandas cannot guess wrong silently.
raw = pd.read_csv(DATA / "trips_raw.csv", dtype=str, keep_default_na=False)
drivers = pd.read_csv(DATA / "drivers.csv")
print(f"loaded {len(raw):,} rows x {raw.shape[1]} columns; every column is {raw['city'].dtype}")

# ── chunk 2: one clock for all timestamps ──
# Three source systems wrote three formats. Look at the shape of the text, then parse each shape on its own.
ts = raw["requested_at"]
is_utc_iso = ts.str.endswith("Z")
is_ist_iso = ts.str.endswith("+05:30")
is_legacy = ts.str.contains("/", regex=False)
is_epoch = ts.str.fullmatch(r"\d+")
assert (is_utc_iso | is_ist_iso | is_legacy | is_epoch).all(), "a timestamp shape we have not seen"

parsed = pd.Series(pd.NaT, index=raw.index, dtype="datetime64[ns, UTC]")
iso = is_utc_iso | is_ist_iso
parsed[iso] = pd.to_datetime(ts[iso], format="ISO8601", utc=True)
# legacy rows carry no zone: the old system ran on Indian time, so we say so out loud.
legacy_local = pd.to_datetime(ts[is_legacy], format="%d/%m/%Y %H:%M").dt.tz_localize("Asia/Kolkata")
parsed[is_legacy] = legacy_local.dt.tz_convert("UTC")
parsed[is_epoch] = pd.to_datetime(ts[is_epoch].astype("int64"), unit="s", utc=True)
raw["requested_at"] = parsed.dt.tz_convert("Asia/Kolkata")     # report in the city's own clock
print("formats seen:", {"utc_iso": int(is_utc_iso.sum()), "ist_iso": int(is_ist_iso.sum()),
                         "legacy": int(is_legacy.sum()), "epoch": int(is_epoch.sum())})
print("span:", raw["requested_at"].min().strftime("%Y-%m-%d %H:%M"), "to", raw["requested_at"].max().strftime("%Y-%m-%d %H:%M"))

# ── chunk 3: spellings and number-shaped text ──
city_map = {
    "bengaluru": "Bengaluru", "bangalore": "Bengaluru", "blr": "Bengaluru",
    "hyderabad": "Hyderabad", "hyd": "Hyderabad", "hyd.": "Hyderabad", "hydrabad": "Hyderabad",
    "mumbai": "Mumbai", "bombay": "Mumbai", "mum": "Mumbai",
    "pune": "Pune", "chennai": "Chennai", "madras": "Chennai",
}
before = raw["city"].nunique()
raw["city"] = raw["city"].str.strip().str.lower().map(city_map)
assert raw["city"].notna().all(), "a spelling is missing from city_map"
raw["status"] = raw["status"].str.lower()
raw["surge_multiplier"] = pd.to_numeric(raw["surge_multiplier"].str.rstrip("x"), errors="coerce")
for col in ["distance_km", "pickup_eta_min", "fare_inr"]:
    raw[col] = pd.to_numeric(raw[col], errors="coerce")
raw["driver_id"] = raw["driver_id"].replace("", pd.NA)
print(f"city spellings {before} -> {raw['city'].nunique()}:", raw["city"].value_counts().to_dict())

# ── chunk 4: duplicates and impossible values ──
n_before = len(raw)
exact = int(raw.duplicated(keep="first").sum())            # identical in every column
raw = raw.drop_duplicates(subset="trip_id", keep="first")   # same trip, any spelling of the timestamp
print(f"duplicates: {exact} exact + {n_before - len(raw) - exact} same trip_id with a different timestamp text -> {len(raw):,} rows left")

raw["bad_fare"] = raw["fare_inr"].le(0)
raw["bad_distance"] = raw["distance_km"].le(0) | raw["distance_km"].gt(150)
raw.loc[raw["bad_fare"], "fare_inr"] = pd.NA            # keep the row, blank the lie, remember we did
raw.loc[raw["bad_distance"], "distance_km"] = pd.NA
print(f"impossible: {int(raw['bad_fare'].sum())} fares <= 0, {int(raw['bad_distance'].sum())} distances <= 0 or > 150 km")

# ── chunk 5: missing values, the driver table, and a saved result ──
print("missing driver_id by status:", raw.groupby("status")["driver_id"].apply(lambda s: round(s.isna().mean(), 3)).to_dict())
raw["no_driver"] = raw["driver_id"].isna()                  # the gap itself is information: keep it as a column
raw["eta_missing"] = raw["pickup_eta_min"].isna()
raw["pickup_eta_min"] = raw["pickup_eta_min"].fillna(raw.groupby("city")["pickup_eta_min"].transform("median"))
raw["surge_missing"] = raw["surge_multiplier"].isna()       # not guessed: analyses skip these rows

trips = raw.merge(drivers[["driver_id", "joined_on", "rating"]], on="driver_id", how="left")
trips["driver_tenure_days"] = (trips["requested_at"].dt.tz_localize(None).dt.normalize()
                               - pd.to_datetime(trips["joined_on"])).dt.days
trips = trips.drop(columns=["joined_on"])
trips.to_parquet(DATA / "trips_clean.parquet", index=False)
print(f"saved {len(trips):,} rows to data/trips_clean.parquet; dtypes:", dict(trips.dtypes.astype(str).value_counts()))

Read the output. Fifty thousand rows in, 49,000 out. The 1,000 removed repeats split into 958 exact copies and 42 that differed only in the seconds shown. The impossible counts are 457 fares and 295 distances. The key line is the one about drivers: 55% of rider cancellations have no driver, but under 1% of completed trips do. That gap is the story, not damage, and it is why no_driver became a column and not a fill.

what the checklist found in the 50,000-row export duplicate trips removed 1,000 (958 exact + 42 re-timed) 1 fares of 0 or below blanked 457 2 distances 0 or >150 km blanked 295 3 surge unreadable, left blank 493 4 missing driver_id, kept as flag 2,528 (55% of cancels) 5 and 21 city spellings became 5 cities. 6
Fig. 4.2 — The cleaning checklist produces a ledger: every problem is counted, and every fix is either a deletion, a blank, or a flag.
  1. Duplicates. 1,000 rows are repeats of trips already in the file. 958 are identical after the times are parsed. 42 differ only because one copy kept seconds and the other did not. Counting them costs nothing; guessing would.
  2. Fares of 0 or below. 457 rows. A fare of 0 or less on a trip is a refund or a bug, not a price. We blank the number, keep the row and remember with a flag.
  3. Distances. 295 rows read 0 km or above 150 km, impossible inside one city. Their mean distance would have been 19.8 km instead of 6.7 km if we had left them.
  4. Surge. 493 rows have no readable multiplier. We do not invent 1.0; analyses that need surge skip them and say how many.
  5. Missing drivers. 2,528 rows, and 55% of rider cancellations have no driver. That is not damage: the rider cancelled before anyone was matched. So the gap becomes a column, no_driver.
  6. Spellings. Bangalore, BLR, bengaluru and the others are one city. The biggest single spelling of Hyderabad held 6,603 trips; the real total is 12,062.

Fig. 4.2 is the ledger the program just printed, drawn to scale. Save a ledger like this with every dataset. When a number in a later slide looks wrong, it tells you which fix to doubt first. The cleaned file is also written for the next chapter: 01d · SQL & the Data Lifecycle continues with the same RideNow data, now as SQL tables.

Quick reference — the cleaning checklist

Types first
Read as text, then convert on purpose. to_numeric(errors="coerce") turns junk into NaN so you can count it.
Timestamps
Classify by shape, parse each shape with an explicit format, localise zone-less text from knowledge, convert to one zone.
Spellings
Lower-case, trim, map through a dictionary, and assert that nothing was left unmapped.
Duplicates
After parsing, drop by the business key (trip_id). 958 exact + 42 re-timed = 1,000 here.
Impossible values
Blank, keep the row, keep a flag. 457 fares, 295 distances.
Missing values
Ask what the gap means. 55% of rider cancels lack a driver because nobody was matched, so it became a flag.
Save
Parquet keeps types and is about four times smaller than CSV here (1.6 MB against 6.7 MB).

05 · The EDA methodQuestion, Plot, Finding, Caveat

Wednesday morning. Priya has trips_clean.parquet: 49,000 trips, one clock, five cities, every gap accounted for. She could now plot everything. She will not, because a pile of plots is how an analyst ends up with fifteen charts and no answer for Marcus. She needs a method that forces each chart to answer one question.

Exploratory data analysis (EDA) is looking at data with questions in hand before you build anything on it. Without a method it turns into plotting everything and describing whatever looks interesting.

The method is a loop with four steps, drawn in Fig. 5.1. Write the question first. Choose the one plot that compares what the question compares. State the finding as a sentence with numbers in it. Then write the caveat: what the plot does not prove.

Question Did riders get less patient? 1 Plot cancel rate by surge band 2 Finding 21.1% -> 24.4% at surge 2.0+ 3 Caveat no experiment, only association 4 the caveat raises the next question: what rode along with surge?
Fig. 5.1 — Every finding in this chapter is one lap of the same four-step loop, shown here with finding 2's real numbers.
  1. Question. Written before any code, as a sentence a manager could ask. Without it, a plot is decoration.
  2. Plot. The one picture that answers that question. Choosing the plot is choosing the comparison.
  3. Finding. One sentence with the numbers in it. 'At surge 2.0+ riders cancel 21.1% of the time before week 5 and 24.4% after.' If the sentence has no number, it is an opinion.
  4. Caveat. What the plot does not prove. It is not modesty; it is the thing that sends you back around the loop. Here it asks which other changes arrived with the surge.

The caveat is the step beginners skip. It is also the step that makes Marcus trust the other three. "Riders cancel more at higher surge" is a finding. "...but we ran no experiment, so something else that rose with surge could be the cause" is a caveat, and it points at the next question.

One tiny chart first

Before the real plots, here is the smallest chart that follows the method. It has four numbers, two labelled axes and a saved file. Two libraries are involved, and it helps to know their jobs. matplotlib draws: figures, axes, labels, saving. seaborn sits on top of it and knows statistical charts, so one call makes a whole bar chart from a table.

Step-by-step: what tiny_plot.py does, in plain English
  1. matplotlib.use("Agg") tells matplotlib to draw into files and never open a window, so the script works on any server.
  2. A four-row table holds the surge multiplier and the cancel rate.
  3. plt.subplots(figsize=(5, 3)) creates an empty figure and one set of axes to draw on.
  4. sns.barplot(...) draws one bar per row onto those axes, in one colour.
  5. set_xlabel and set_ylabel label the axes. A chart without axis labels is not a finding.
  6. savefig writes a PNG into the figures folder.
tiny_plot.pyruns offline
# tiny_plot.py -- the smallest honest chart: four numbers, labelled axes, saved to a file.
# pip install "matplotlib>=3.9" "seaborn>=0.13,<0.14" "pandas>=3,<4"
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df = pd.DataFrame({"surge": ["1.0", "1.5", "2.0", "3.0"], "cancel_pct": [5.1, 8.5, 16.1, 37.9]})
fig, ax = plt.subplots(figsize=(5, 3))
sns.barplot(data=df, x="surge", y="cancel_pct", ax=ax, color="#4C78A8")
ax.set_xlabel("surge multiplier"); ax.set_ylabel("rider cancel rate (%)")
fig.tight_layout()
fig.savefig(Path(__file__).parent / "figures" / "tiny_plot.png", dpi=100)
print("saved figures/tiny_plot.png")
what it printed
saved figures/tiny_plot.png

Read the output. One line: the file was saved. Open figures/tiny_plot.png and you see four bars rising from 5.1 to 37.9. That is already a finding in picture form. The remaining work is writing it as a sentence and deciding what it does not prove.

Choosing the plot is choosing the comparison. The table says which chart fits which question. All five of these appear in the findings later.

Decision table: which plot for which question
PlotChoose whenAvoid whenUsed here for
Bar chartComparing a number across a few named groupsMany groups or a time axisCancel rate by surge band, city, tenure
Line chartOne number changing over ordered timeUnordered categoriesShare of high-surge trips by week
HeatmapA number across two categories at once, such as weekday by hourCells with few rows, which look dramatic but are noiseChange in cancel rate by weekday and hour
HistogramThe shape of one number, to see outliers and skewComparing groups with different sizes without scalingSpotting the 19.8 km distance problem
Scatter plotWhether two numbers move togetherHundreds of thousands of points, which hide structureNot needed in this lab

One reminder from Module 01b applies to every chart in this chapter: an average can hide the shape of the data. The 19.8 km mean distance before cleaning and 6.7 km after is the same lesson. Always look at a count next to every rate, which is why every bar in the findings carries its trip count somewhere.

The average that lies: Simpson's paradox, with 200 toy trips

Priya's team already has a theory: "sedans are the problem, they cancel more." Before she plots 49,000 real trips against that theory, she tests the logic on a table small enough to do by hand. The small version shows how a true-looking average can point the wrong way.

Sharpen your pencil

Here are 200 toy trips. Work out each cancel rate by hand: cancelled divided by trips, as a percentage. Three are given.

Auto, day: 8 cancelled of 808 ÷ 80 = 10%
Sedan, day: 1 cancelled of 201 ÷ 20 = 5%
Auto, night: 8 cancelled of 208 ÷ 20 = 40%
Sedan, night: 24 cancelled of 80
Auto overall: day plus night together (80 + 20 trips, 8 + 8 cancelled)
Sedan overall: day plus night together (20 + 80 trips, 1 + 24 cancelled)
Which vehicle looks better in each half? Overall?
Check your answers
Sedan, night: 24 cancelled of 8024 ÷ 80 = 30%
Auto overall(8 + 8) ÷ (80 + 20) = 16 ÷ 100 = 16%
Sedan overall(1 + 24) ÷ (20 + 80) = 25 ÷ 100 = 25%
Which looks better?In the day, sedan (5% against 10%). At night, sedan (30% against 40%). Overall, auto (16% against 25%). The verdict flips.

If you got 16% and 25% and still feel uneasy, good. The picture and the questions below explain why the unease is right.

all trips together 16% auto 16/100 25% sedan 25/100 1 split by time of day 10% auto 8/80 5% sedan 1/20 day 40% auto 8/20 30% sedan 24/80 night 2 3 sedan is lower in both halves, higher overall sedan looks worse
Fig. 5.2 — Two hundred toy trips reverse the verdict: sedans cancel more overall (25% against 16%) and less within every time of day.
  1. Together. 100 auto trips with 16 cancelled and 100 sedan trips with 25 cancelled. Read alone, this says sedans are worse.
  2. By day. Auto: 8 cancelled out of 80 = 10%. Sedan: 1 out of 20 = 5%. The sedan is better. Day trips are quiet and few cancel.
  3. By night. Auto: 8 out of 20 = 40%. Sedan: 24 out of 80 = 30%. Better again. Night is where everyone cancels more, and 80 of the 100 sedan trips are at night, so their overall number is dragged up by when they run, not by what they are.

The toy table was built so the paradox appears, but the shape is common. Night trips cancel more for everyone, and marker 3 in Fig. 5.2 shows 80 of the 100 sedan trips happen at night. The real data has the same structure, and finding 5 later checks it with real numbers.

Questions you might be asking now

The toy trips and the real numbers raise three questions most first-time readers ask. Every answer uses the 200 toy trips or the real Friday-to-Sunday rates, with each calculation written out.

How can the overall number go the opposite way from both of its parts?

The overall rate is a weighted average of the parts, and the two vehicles use very different weights. Sedan trips are mostly night trips, and night trips cancel more for everyone. So the sedan average is pulled up by when it runs, not by what it is.

  1. Sedan weights. 20 of its 100 trips are day (20%), 80 are night (80%).
  2. Sedan overall. 0.20 × 5% + 0.80 × 30% = 1% + 24% = 25%.
  3. Auto weights. 80 day (80%), 20 night (20%).
  4. Auto overall. 0.80 × 10% + 0.20 × 40% = 8% + 8% = 16%.
Same two rates, different weights
Day rateNight rateShare at nightOverall
Auto10%40%20%16%
Sedan5%30%80%25%

The honest limit: splitting by day and night is one choice. A different hidden factor, such as city, could produce the same effect inside each half. The split helps only if the factor you split by is the real confounder.

When two groups differ in how their trips are spread across hours, compare them inside each hour, not in total.

The weekend rate went from 10.5% to 13.0%. How do I know that is not just luck?

Because each rate comes with a plus-or-minus range, and the two ranges do not overlap. The gap is 5.7 standard errors wide, far beyond what luck makes. The program rate_noise.py prints every number below.

  1. The measured rates. Friday to Sunday: 10.54% of 10,892 trips in weeks 1-4, and 12.97% of 11,920 trips in weeks 5-8.
  2. Standard error of a rate. √(p × (1 − p) ÷ n), where p is the rate and n the trips. For weeks 1-4: √(0.1054 × 0.8946 ÷ 10,892) = √0.00000866 = 0.00294.
  3. The 95% range is about 1.96 standard errors either side. 1.96 × 0.00294 = 0.0058, so 10.54% plus or minus 0.58 points. Weeks 5-8 give 12.97% plus or minus 0.60 points.
  4. The gap between the two rates. 12.97 − 10.54 = 2.43 points. Its standard error is √(0.00294² + 0.00308²) = 0.0043, so the gap is 0.0243 ÷ 0.0043 = 5.7 standard errors.
8% 10% 12% 14% 16% cancel rate, Friday to Sunday weeks 1-4: 10.54% (n = 10,892) weeks 5-8: 12.97% (n = 11,920) 1 2 3
Fig. 5.3 — The two measured rates come with a plus-or-minus range of about 0.6 points each, and the ranges do not touch.
  1. Weeks 1-4. 10.54% of 10,892 trips cancelled. The 95% range is 10.54% plus or minus 0.58 points, 9.96% to 11.12%.
  2. Weeks 5-8. 12.97% of 11,920 trips cancelled, plus or minus 0.60 points, 12.37% to 13.57%.
  3. The gap. There is clear space between the two ranges. The difference, 2.43 points, is 5.7 standard errors, far beyond what luck alone is likely to make. Module 01b explains why a gap of two or three standard errors is the usual line.

Symbol key: p is the cancel rate as a fraction (0.1054), n is the number of trips, √ is square root, × is multiply, ÷ is divide, and 1.96 is the multiplier that gives a 95% range.

The honest limit: this only rules out luck inside this sample. It says nothing about why the rate moved. It also assumes each trip is an independent event, which is not exactly true when two trips share a rainstorm.

A gap more than about two or three standard errors wide is probably not luck; 5.7 is not close.

Why are some squares in the weekday-by-hour heatmap left blank, and why do the others jump around?

A square with few trips has a wide plus-or-minus range, so its rate wobbles from luck alone. We leave squares with fewer than 100 trips blank so they cannot dominate the colours.

  1. Take one square. All Friday-2pm trips over eight weeks: 135 trips, 11.9% cancelled.
  2. Its range. 1.96 × √(0.119 × 0.881 ÷ 135) = 1.96 × 0.0279 = 0.055, so 11.9% plus or minus 5.5 points.
  3. Compare to the big groups. The whole Friday-to-Sunday group had a range of plus or minus 0.6 points.
  4. Before versus after. The heatmap splits those 135 trips again into before and after, so each half has about 65 trips. A difference of several points there is within noise.

The honest limit: leaving cells blank is a judgement. Pick the threshold before you look at the plot, and say what it was.

A dramatic colour in a small cell is usually noise; look at the cell's trip count before you believe it.

Quick reference — EDA method

The loop
Question, plot, finding (a sentence with numbers), caveat (what it does not prove).
matplotlib vs seaborn
matplotlib draws and saves; seaborn makes statistical charts from tables in one call.
Show counts
A rate without its trip count is a claim without evidence.
Simpson's paradox
An overall rate can reverse inside every part when the groups differ in mix. Compare within parts.
Standard error
√(p(1−p)/n). A 95% range is about 1.96 of them either side.
Small cells
Few trips means a wide range. Blank them or say their n.

06 · Five findingsWednesday Afternoon: Answer Marcus

Priya has the method and the clean file. It is Wednesday afternoon and the board meets Thursday. She turns Marcus's one question into five smaller ones: when did it jump, did riders change, which city, which drivers, and is the "sedans are the problem" theory true? Each one gets a plot, a sentence and a caveat. She builds the program in five chunks, one more finding at a time.

This section runs the EDA loop five times on the real trips. Each lap produces one figure, one sentence with numbers, and one caveat, and the program saves them all.

Build it in chunks

We build eda_report.py in five chunks. Each one runs on its own and prints its findings. It needs data/trips_clean.parquet, which clean_trips.py wrote. Figures go to a figures folder.

  1. Chunk 1 — load the clean file, add the columns every question needs, and define what a finding is

    Every finding will be a record with the same fields, so the shape is written down first. This is a Pydantic model, which the next section explains properly. For now, read it as "a typed form that a finding must fill in".

    Step-by-step: what chunk 1 does, in plain English
    1. Import the libraries. matplotlib.use("Agg") makes plots draw to files.
    2. Define Finding: an id from 1 to 5, the question, a finding sentence of at least 20 characters, an evidence dictionary of numbers, a caveat of at least 10 characters, a figure path and an action.
    3. Define Report: the row count plus exactly five findings.
    4. Load the Parquet file and add helper columns: hour, weekday (Monday is 0), week number, an after flag for weeks 5-8, cancelled flags, and a flag for the Friday-Saturday 22:00-to-03:00 window.
    5. Set a plain seaborn theme, an empty list for findings, and a small percent helper.
    6. Print the overall rate before and after, and the Friday-to-Sunday rate before and after.
    eda_report.py — chunk 1runs offline
    # eda_report.py -- five findings for the CEO, each with a figure, a caveat and a structured record.
    # pip install "pandas>=3,<4" "pyarrow>=20" "matplotlib>=3.9" "seaborn>=0.13,<0.14" "pydantic>=2.7,<3"
    # Needs data/trips_clean.parquet: run clean_trips.py first.
    from pathlib import Path
    
    import matplotlib
    matplotlib.use("Agg")                      # draw to files, never to a window
    import matplotlib.pyplot as plt
    import pandas as pd
    import seaborn as sns
    from pydantic import BaseModel, Field
    
    HERE = Path(__file__).parent
    FIG = HERE / "figures"
    FIG.mkdir(exist_ok=True)
    
    # ── chunk 1: load, add the columns every question needs, define what a finding is ──
    class Finding(BaseModel):
        id: int = Field(ge=1, le=5)
        question: str
        finding: str = Field(min_length=20)
        evidence: dict[str, float]              # the numbers that prove it
        caveat: str = Field(min_length=10)      # what this does NOT show
        figure: str
        action: str
    
    class Report(BaseModel):
        rows_analysed: int = Field(gt=0)
        findings: list[Finding] = Field(min_length=5, max_length=5)
    
    t = pd.read_parquet(HERE / "data" / "trips_clean.parquet")
    t["hour"] = t["requested_at"].dt.hour
    t["dow"] = t["requested_at"].dt.dayofweek                       # Monday = 0
    t["week"] = (t["requested_at"].dt.tz_localize(None) - pd.Timestamp("2026-08-03")).dt.days // 7 + 1
    t["after"] = t["week"] >= 5                                       # weeks 5-8 versus weeks 1-4
    t["cancelled"] = t["status"] != "completed"
    t["rider_cx"] = t["status"] == "cancelled_rider"
    t["driver_cx"] = t["status"] == "cancelled_driver"
    t["fri_sat_night"] = t["dow"].isin([4, 5]) & ((t["hour"] >= 22) | (t["hour"] < 3))
    sns.set_theme(style="whitegrid", context="talk")
    findings: list[Finding] = []
    pct = lambda x: round(100 * float(x), 1)
    fri_sun = t[t.dow >= 4]                                           # the dashboard's "weekend": Friday to Sunday
    print(f"{len(t):,} clean trips; all days {pct(t[~t.after].cancelled.mean())}% -> {pct(t[t.after].cancelled.mean())}%; "
          f"Fri-Sun {pct(fri_sun[~fri_sun.after].cancelled.mean())}% -> {pct(fri_sun[fri_sun.after].cancelled.mean())}%")
    

    pydantic.BaseModel with Field limits, read_parquet and dt.dayofweek.

    Run python3 eda_report.py (after clean_trips.py). You should see one line:

    what it printed
    49,000 clean trips; all days 10.0% -> 11.0%; Fri-Sun 10.5% -> 13.0%
    

    Read it first. Over all days the rate barely moved, 10.0% to 11.0%. Only the Friday-to-Sunday slice jumped, 10.5% to 13.0%. This is the number on Marcus's dashboard, and its small size on all days is the first hint that the jump is concentrated.

  2. Chunk 2 — findings 1 and 2: when it jumped, and what rode along with it

    The first question is about time. The second question looks for the nearest suspect: surge pricing, which the dashboard also tracks. Both are compared before and after week 5, the start of the last four weeks.

    Step-by-step: what chunk 2 does, in plain English
    1. Build a weekday-by-hour table of cancel rates for before and after, subtract to get the change in percentage points, and blank squares with under 100 trips.
    2. Draw it as a seaborn heatmap with a diverging colour scale centred on zero, label the axes, save f1_when.png.
    3. Compare the Friday-Saturday 22:00-03:00 window with the rest of the week, and count the extra cancellations the window produced beyond the old rate.
    4. Create a Finding for question 1 with the four rates and the extra counts as evidence, and a caveat.
    5. For question 2, group rider cancellations by surge band and compute the share of window trips at surge 2.0 or more, per week.
    6. Draw the two panels side by side (bar chart and line chart), save f2_surge.png, and record finding 2 with its caveat.
    eda_report.py — chunk 2runs offline
    # ── chunk 2: findings 1 and 2 -- WHEN it jumped, and what rode along with it ──
    cell = t.pivot_table(index="dow", columns=["after", "hour"], values="cancelled", aggfunc="mean")
    delta = (cell[True] - cell[False]) * 100                         # percentage-point change per weekday-hour cell
    counts = t.pivot_table(index="dow", columns="hour", values="trip_id", aggfunc="size")
    delta = delta.where(counts >= 100)                               # too few trips in a cell = noise, leave it blank
    fig, ax = plt.subplots(figsize=(12, 4.5))
    sns.heatmap(delta, cmap="RdBu_r", center=0, ax=ax, cbar_kws={"label": "change in cancel rate (points)"})
    ax.set_yticklabels(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], rotation=0)
    ax.set_xlabel("hour of day (Indian time)"); ax.set_ylabel("")
    fig.tight_layout(); fig.savefig(FIG / "f1_when.png", dpi=110); plt.close(fig)
    win = t[t.fri_sat_night]
    def extra_cancels(part):                                          # cancels beyond what the weeks 1-4 rate would predict
        old_rate = part[~part.after].cancelled.mean()
        return float(part[part.after].cancelled.sum() - old_rate * part.after.sum())
    rest = t[~t.fri_sat_night]
    findings.append(Finding(id=1, question="When exactly did cancellations jump?",
        finding="The jump lives in the 22:00-to-03:00 window on Fridays and Saturdays, not in 'the weekend' as a whole.",
        evidence={"window_before_pct": pct(win[~win.after].cancelled.mean()), "window_after_pct": pct(win[win.after].cancelled.mean()),
                  "rest_before_pct": pct(rest[~rest.after].cancelled.mean()), "rest_after_pct": pct(rest[rest.after].cancelled.mean()),
                  "window_share_of_trips_pct": pct(len(win) / len(t)),
                  "extra_cancels_window": round(extra_cancels(win)), "extra_cancels_fri_sun": round(extra_cancels(fri_sun))},
        caveat="Eight weeks only; one policy change and one hiring drive both start in week 5.",
        figure="figures/f1_when.png", action="Report the window, not the weekend."))
    print("F1", findings[-1].evidence)
    
    bands = pd.cut(t["surge_multiplier"], [0.9, 1.1, 1.3, 1.6, 2.1, 2.6, 3.1], labels=["1.0", "1.2", "1.5", "2.0", "2.5", "3.0"])
    by_band = t.groupby(bands, observed=True).rider_cx.agg(["mean", "size"])
    hi = t[t.surge_multiplier >= 2]
    share = win.assign(hi=win.surge_multiplier >= 2).groupby("week").hi.mean() * 100
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(13, 4.5))
    sns.barplot(x=by_band.index.astype(str), y=by_band["mean"] * 100, color="#4C78A8", ax=a1)
    a1.set_xlabel("surge multiplier"); a1.set_ylabel("rider cancel rate (%)")
    sns.lineplot(x=share.index, y=share.values, marker="o", color="#E45756", ax=a2)
    a2.set_xlabel("week"); a2.set_ylabel("trips at surge 2.0+ (%)"); a2.set_title("Fri/Sat 22:00-03:00 window", fontsize=13); a2.axvline(4.5, ls="--", color="grey")
    fig.tight_layout(); fig.savefig(FIG / "f2_surge.png", dpi=110); plt.close(fig)
    findings.append(Finding(id=2, question="Did riders become less patient, or did more of them meet a high surge?",
        finding="Riders barely changed: at surge 2.0+ they cancel about the same share before and after. What changed is how many trips got surge 2.0+.",
        evidence={"rate_surge_1.0_pct": pct(by_band["mean"].iloc[0]), "rate_surge_3.0_pct": pct(by_band["mean"].iloc[-1]),
                  "hi_surge_cancel_before_pct": pct(hi[~hi.after].rider_cx.mean()), "hi_surge_cancel_after_pct": pct(hi[hi.after].rider_cx.mean()),
                  "night_hi_surge_share_wk1_pct": round(float(share.loc[1]), 1), "night_hi_surge_share_wk8_pct": round(float(share.loc[8]), 1)},
        caveat="Shows association inside this export; it cannot prove surge caused the cancels (no experiment).",
        figure="figures/f2_surge.png", action="Review the week-5 surge rules for the Fri/Sat night window."))
    print("F2", findings[-1].evidence)
    

    pivot_table with two-level columns, pd.cut (turn a number into bands), sns.heatmap and sns.barplot.

    Two new lines print the evidence for findings 1 and 2:

    what it printed
    F1 {'window_before_pct': 15.9, 'window_after_pct': 25.2, 'rest_before_pct': 9.1, 'rest_after_pct': 9.1, 'window_share_of_trips_pct': 12.0, 'extra_cancels_window': 284.0, 'extra_cancels_fri_sun': 290.0}
    F2 {'rate_surge_1.0_pct': 5.1, 'rate_surge_3.0_pct': 37.9, 'hi_surge_cancel_before_pct': 21.1, 'hi_surge_cancel_after_pct': 24.4, 'night_hi_surge_share_wk1_pct': 15.2, 'night_hi_surge_share_wk8_pct': 59.1}
    

    Finding 1. Inside the window, the rate went from 15.9% to 25.2%. Outside it, 9.1% to 9.1%. The window holds 12% of trips and 284 of the roughly 290 extra cancellations.

    Fri/Sat, 22:00 to 03:00 15.9% 25.2% weeks 1-4 weeks 5-8 1 every other hour of the week 9.1% 9.1% weeks 1-4 weeks 5-8 2 The window is 12% of trips but holds 284 of the 290 extra cancellations. 3
    Fig. 6.1 — Finding 1: the jump is one five-hour window; everywhere else the rate did not move at all.
    1. The window. On Fridays and Saturdays between 22:00 and 03:00 the cancel rate went from 15.9% (451 of 2,833 trips) to 25.2% (772 of 3,065).
    2. Everything else. Outside the window the rate was 9.1% in weeks 1-4 and 9.1% in weeks 5-8. No change.
    3. Where the extra cancellations are. If weeks 5-8 had kept the old rate, the window would have had about 488 cancellations, not 772. That is 284 extra, out of 290 extra across all of Friday to Sunday. The window is only 12% of all trips.

    Read the left half of Fig. 6.1 first: marker 1 shows the window. The right half, marker 2, shows the rest of the week standing still. The number to remember sits at marker 3.

    Finding 2. Rider cancellations climb steeply with surge, 5.1% at 1.0x to 37.9% at 3.0x. At surge 2.0 or more riders cancelled 21.1% of the time before and 24.4% after, so riders barely changed. What changed is exposure: the share of window trips at surge 2.0 or more went from about 15% to about 59%, in one step between weeks 4 and 5.

    rider cancel rate by surge 5.1 1.0 6.4 1.2 8.5 1.5 16.1 2.0 24.8 2.5 37.9 3.0 surge multiplier 1 Fri/Sat window: trips at surge 2.0+ 1 2 3 4 5 6 7 8 15% 59% week 2 new rules 3
    Fig. 6.2 — Finding 2: riders react to surge the same way all along; what changed in week 5 is how many of them were charged a high surge.
    1. Dose and response. Rider cancel rate climbs with every step of surge: 5.1% at 1.0x, 16.1% at 2.0x, 37.9% at 3.0x. More dose, more cancelling, a pattern that points toward cause.
    2. The exposure. In the Friday-Saturday window, 15% of trips were at surge 2.0 or more in week 1. From week 5 it is 57% to 61% every week.
    3. The break. The dashed line sits between weeks 4 and 5. Before it, the share is flat near 16%; after it, flat near 59%. A sudden step on a known date smells like a rule change, not a gradual shift in riders. Whether surge rules changed that week is something to confirm with the pricing team, not something the data proves.

    In Fig. 6.2, the left panel (marker 1) is the dose-and-response. The right panel (marker 2) is the exposure, and the dashed line at marker 3 is where it steps. The caveat is in the program: no experiment, so this is association.

  3. Chunk 3 — findings 3 and 4: where it happens and who is driving

    Finding 2 explains the rider side. Cancellations also come from drivers, about 2.5% of trips. Two more questions come from the cleaned data: which city, which kind of driver. Both only work because we fixed the spellings and merged the drivers table.

    Step-by-step: what chunk 3 does, in plain English
    1. Group by the clean city: trip count, driver cancel rate and mean pickup wait.
    2. Draw the city bar chart and save f3_city.png.
    3. Record finding 3: Hyderabad's trips, rate and wait against the other four cities.
    4. Keep trips with a known driver, cut tenure into under 30 days, 30-89 days and 90 or more, and compute the driver cancel rate in each.
    5. Compute the share of window trips handled by drivers under 30 days old, before and after.
    6. Draw the tenure bar chart, save f4_rookies.png, and record finding 4 with its caveat.
    eda_report.py — chunk 3runs offline
    # ── chunk 3: findings 3 and 4 -- WHERE and WHO (cleaned cities, merged drivers) ──
    by_city = t.groupby("city").agg(trips=("trip_id", "size"), driver_cx=("driver_cx", "mean"), eta=("pickup_eta_min", "mean"))
    fig, ax = plt.subplots(figsize=(8, 4.5))
    sns.barplot(x=by_city.index, y=by_city["driver_cx"] * 100, color="#59A14F", ax=ax)
    ax.set_ylabel("driver cancel rate (%)"); ax.set_xlabel("")
    fig.tight_layout(); fig.savefig(FIG / "f3_city.png", dpi=110); plt.close(fig)
    findings.append(Finding(id=3, question="Which city is the problem once the spellings are fixed?",
        finding="Hyderabad is the second-biggest city, not a footnote, and its drivers cancel most because pickups take longest.",
        evidence={"hyderabad_trips": float(by_city.loc["Hyderabad", "trips"]), "hyderabad_driver_cx_pct": pct(by_city.loc["Hyderabad", "driver_cx"]),
                  "others_driver_cx_pct": pct(by_city.drop("Hyderabad").driver_cx.mean()),
                  "hyderabad_mean_eta_min": round(float(by_city.loc["Hyderabad", "eta"]), 1),
                  "others_mean_eta_min": round(float(by_city.drop("Hyderabad").eta.mean()), 1)},
        caveat="ETA is the quoted wait, not the measured one; a city average hides local hotspots.",
        figure="figures/f3_city.png", action="Add supply or relax pickup radius in Hyderabad."))
    print("F3", findings[-1].evidence)
    
    known = t.dropna(subset=["driver_tenure_days"]).copy()
    known["tenure"] = pd.cut(known.driver_tenure_days, [-1, 29, 89, 5000], labels=["under 30 d", "30-89 d", "90+ d"])
    by_ten = known.groupby("tenure", observed=True).driver_cx.agg(["mean", "size"])
    rook_share = known.assign(r=known.driver_tenure_days < 30).groupby(["fri_sat_night", "after"]).r.mean() * 100
    fig, ax = plt.subplots(figsize=(8, 4.5))
    sns.barplot(x=by_ten.index.astype(str), y=by_ten["mean"] * 100, color="#F28E2B", ax=ax)
    ax.set_ylabel("driver cancel rate (%)"); ax.set_xlabel("driver tenure on trip day")
    fig.tight_layout(); fig.savefig(FIG / "f4_rookies.png", dpi=110); plt.close(fig)
    findings.append(Finding(id=4, question="Do new drivers cancel more, and are there more of them at the bad hours?",
        finding="Drivers under 30 days old cancel about three times as often, and they now cover about one in five Fri/Sat-night trips.",
        evidence={"rookie_cx_pct": pct(by_ten.loc["under 30 d", "mean"]), "veteran_cx_pct": pct(by_ten.loc["90+ d", "mean"]),
                  "rookie_share_window_before_pct": round(float(rook_share.loc[(True, False)]), 1),
                  "rookie_share_window_after_pct": round(float(rook_share.loc[(True, True)]), 1)},
        caveat="Rows with no driver_id (riders who cancelled before a match) are excluded; tenure and hiring date overlap.",
        figure="figures/f4_rookies.png", action="Pair rookies with short pickups at night."))
    print("F4", findings[-1].evidence)
    

    groupby().agg with several named outputs and dropna(subset=...) to keep only known drivers.

    Two more lines print the evidence for findings 3 and 4:

    what it printed
    F3 {'hyderabad_trips': 11818.0, 'hyderabad_driver_cx_pct': 3.2, 'others_driver_cx_pct': 2.2, 'hyderabad_mean_eta_min': 9.2, 'others_mean_eta_min': 6.0}
    F4 {'rookie_cx_pct': 8.5, 'veteran_cx_pct': 2.3, 'rookie_share_window_before_pct': 1.6, 'rookie_share_window_after_pct': 19.2}
    

    Finding 3. Hyderabad has 11,818 trips, second only to Bengaluru, and its drivers cancel 3.2% of trips against about 2.2% elsewhere. Its quoted pickup wait averages 9.2 minutes against 6.0.

    Finding 4. Drivers under 30 days old cancel 8.5% of trips, against 2.3% for veterans. They covered 1.6% of window trips before week 5 and 19.2% after.

    driver cancel rate by city 2.2% Blr 2.5% Che 3.2% Hyd 2.1% Mum 2.1% Pun Hyd: 11,818 trips, pickup 9.2 min (other cities: 6.0 min) 1 driver cancel rate by tenure 8.5% under 30 d 2.1% 30-89 d 2.3% 90+ d rookies in window: 1.6% -> 19.2% 2 3
    Fig. 6.3 — Findings 3 and 4: one city and one kind of driver carry a driver-side cancel rate well above the rest.
    1. A city that was hiding. After the spellings are merged, Hyderabad has 11,818 trips, the second-largest city, and drivers there cancel 3.2% of trips against about 2.2% elsewhere. Its quoted pickup wait averages 9.2 minutes against 6.0.
    2. New drivers. Drivers in their first 30 days cancel 8.5% of trips. Drivers with 30 to 89 days cancel 2.1% and veterans 2.3%, so the difference is a first-month effect.
    3. More of them at the bad hour. In the Friday-Saturday window, drivers under 30 days old covered 1.6% of known-driver trips in weeks 1-4 and 19.2% in weeks 5-8. Rookies and the surge rules arrived together, which is why finding 1 cannot name one cause.

    Fig. 6.3 puts both on one canvas. The left panel, marker 1, is the city. The right panel, marker 2, is tenure. The small note at marker 3 is why this matters now.

  4. Chunk 4 — finding 5: the average that lies

    The team's theory, "sedans cancel more", gets tested with the method from the toy table. Finding 5 is the real version of Fig. 5.2.

    Step-by-step: what chunk 4 does, in plain English
    1. Label each trip day or night; night is 22:00 to 04:59.
    2. Compute the cancel rate per vehicle type overall, then per day-part and vehicle type, and the share of each vehicle's trips that are at night.
    3. Draw grouped bars by day-part, save f5_simpson.png.
    4. Record finding 5 with all eight numbers, and the caveat that two day-parts are a coarse split.
    eda_report.py — chunk 4runs offline
    # ── chunk 4: finding 5 -- the average that lies (Simpson's paradox) ──
    t["daypart"] = pd.Series(["night" if (h >= 22 or h < 5) else "day" for h in t.hour], index=t.index)
    overall = t.groupby("vehicle_type").cancelled.mean() * 100
    split = t.groupby(["daypart", "vehicle_type"]).cancelled.mean().unstack() * 100
    mix = t.groupby("vehicle_type").daypart.apply(lambda s: (s == "night").mean() * 100)
    fig, ax = plt.subplots(figsize=(8, 4.5))
    plot_df = split.stack().rename("rate").reset_index()
    sns.barplot(data=plot_df, x="daypart", y="rate", hue="vehicle_type", ax=ax)
    ax.set_ylabel("cancel rate (%)"); ax.set_xlabel("")
    fig.tight_layout(); fig.savefig(FIG / "f5_simpson.png", dpi=110); plt.close(fig)
    findings.append(Finding(id=5, question="Are sedans worse than autos for cancellations?",
        finding="Overall sedans cancel more, but inside both day and night they cancel less; they simply run at night.",
        evidence={"sedan_overall_pct": round(float(overall["sedan"]), 1), "auto_overall_pct": round(float(overall["auto"]), 1),
                  "sedan_day_pct": round(float(split.loc["day", "sedan"]), 1), "auto_day_pct": round(float(split.loc["day", "auto"]), 1),
                  "sedan_night_pct": round(float(split.loc["night", "sedan"]), 1), "auto_night_pct": round(float(split.loc["night", "auto"]), 1),
                  "sedan_night_trip_share_pct": round(float(mix["sedan"]), 1), "auto_night_trip_share_pct": round(float(mix["auto"]), 1)},
        caveat="Two day-parts are a coarse split; a third hidden factor could still remain.",
        figure="figures/f5_simpson.png", action="Do not re-price sedans on the overall number."))
    print("F5", findings[-1].evidence)
    

    groupby on two keys followed by unstack, which turns one key into columns.

    One more line prints the evidence for finding 5:

    what it printed
    F5 {'sedan_overall_pct': 13.3, 'auto_overall_pct': 9.9, 'sedan_day_pct': 6.7, 'auto_day_pct': 8.9, 'sedan_night_pct': 17.0, 'auto_night_pct': 21.6, 'sedan_night_trip_share_pct': 63.5, 'auto_night_trip_share_pct': 7.3}
    

    Overall, sedans cancel more (13.3%) than autos (9.9%). By day, sedans cancel less (6.7% against 8.9%). By night, less again (17.0% against 21.6%). And 63.5% of sedan trips are at night, against 7.3% of auto trips. Same paradox as the toy table, with real numbers: the "sedan problem" is a night problem.

  5. Chunk 5 — save the five findings as JSON, checked

    The last step hands over the findings in a form a program can read. The next section explains why this is more than a nicety. Here it is the five lines that write and re-read the file.

    Step-by-step: what chunk 5 does, in plain English
    1. Build a Report from the row count and the five findings. Pydantic validates every field; a bad one raises an error here.
    2. model_dump_json(indent=2) turns the report into formatted JSON text, written to findings.json.
    3. model_validate_json reads the file back and validates it again, as a downstream consumer would.
    4. Print how many findings were read back and how many fields each has.
    eda_report.py — chunk 5runs offline
    # ── chunk 5: save the findings as validated JSON ──
    report = Report(rows_analysed=len(t), findings=findings)           # validation runs here; bad data raises
    (HERE / "findings.json").write_text(report.model_dump_json(indent=2))
    again = Report.model_validate_json((HERE / "findings.json").read_text())   # a consumer re-checks on the way in
    print(f"wrote findings.json: {len(again.findings)} findings, {again.rows_analysed:,} rows; schema has", len(Report.model_json_schema()["$defs"]["Finding"]["properties"]), "fields per finding")
    

    model_dump_json and model_validate_json — write and read validated JSON.

    The last line confirms the save:

    what it printed
    wrote findings.json: 5 findings, 49,000 rows; schema has 7 fields per finding
    

The whole program

Lines 1–16 are the imports and set-up, 17–46 chunk 1, 47–90 chunk 2, 91–123 chunk 3, 124–143 chunk 4, 144–148 chunk 5. Every chunk starts with a # ── chunk n ── comment. This is the file saved as code/01c-python-for-data/eda_report.py.

eda_report.pyruns offline
# eda_report.py -- five findings for the CEO, each with a figure, a caveat and a structured record.
# pip install "pandas>=3,<4" "pyarrow>=20" "matplotlib>=3.9" "seaborn>=0.13,<0.14" "pydantic>=2.7,<3"
# Needs data/trips_clean.parquet: run clean_trips.py first.
from pathlib import Path

import matplotlib
matplotlib.use("Agg")                      # draw to files, never to a window
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from pydantic import BaseModel, Field

HERE = Path(__file__).parent
FIG = HERE / "figures"
FIG.mkdir(exist_ok=True)

# ── chunk 1: load, add the columns every question needs, define what a finding is ──
class Finding(BaseModel):
    id: int = Field(ge=1, le=5)
    question: str
    finding: str = Field(min_length=20)
    evidence: dict[str, float]              # the numbers that prove it
    caveat: str = Field(min_length=10)      # what this does NOT show
    figure: str
    action: str

class Report(BaseModel):
    rows_analysed: int = Field(gt=0)
    findings: list[Finding] = Field(min_length=5, max_length=5)

t = pd.read_parquet(HERE / "data" / "trips_clean.parquet")
t["hour"] = t["requested_at"].dt.hour
t["dow"] = t["requested_at"].dt.dayofweek                       # Monday = 0
t["week"] = (t["requested_at"].dt.tz_localize(None) - pd.Timestamp("2026-08-03")).dt.days // 7 + 1
t["after"] = t["week"] >= 5                                       # weeks 5-8 versus weeks 1-4
t["cancelled"] = t["status"] != "completed"
t["rider_cx"] = t["status"] == "cancelled_rider"
t["driver_cx"] = t["status"] == "cancelled_driver"
t["fri_sat_night"] = t["dow"].isin([4, 5]) & ((t["hour"] >= 22) | (t["hour"] < 3))
sns.set_theme(style="whitegrid", context="talk")
findings: list[Finding] = []
pct = lambda x: round(100 * float(x), 1)
fri_sun = t[t.dow >= 4]                                           # the dashboard's "weekend": Friday to Sunday
print(f"{len(t):,} clean trips; all days {pct(t[~t.after].cancelled.mean())}% -> {pct(t[t.after].cancelled.mean())}%; "
      f"Fri-Sun {pct(fri_sun[~fri_sun.after].cancelled.mean())}% -> {pct(fri_sun[fri_sun.after].cancelled.mean())}%")

# ── chunk 2: findings 1 and 2 -- WHEN it jumped, and what rode along with it ──
cell = t.pivot_table(index="dow", columns=["after", "hour"], values="cancelled", aggfunc="mean")
delta = (cell[True] - cell[False]) * 100                         # percentage-point change per weekday-hour cell
counts = t.pivot_table(index="dow", columns="hour", values="trip_id", aggfunc="size")
delta = delta.where(counts >= 100)                               # too few trips in a cell = noise, leave it blank
fig, ax = plt.subplots(figsize=(12, 4.5))
sns.heatmap(delta, cmap="RdBu_r", center=0, ax=ax, cbar_kws={"label": "change in cancel rate (points)"})
ax.set_yticklabels(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], rotation=0)
ax.set_xlabel("hour of day (Indian time)"); ax.set_ylabel("")
fig.tight_layout(); fig.savefig(FIG / "f1_when.png", dpi=110); plt.close(fig)
win = t[t.fri_sat_night]
def extra_cancels(part):                                          # cancels beyond what the weeks 1-4 rate would predict
    old_rate = part[~part.after].cancelled.mean()
    return float(part[part.after].cancelled.sum() - old_rate * part.after.sum())
rest = t[~t.fri_sat_night]
findings.append(Finding(id=1, question="When exactly did cancellations jump?",
    finding="The jump lives in the 22:00-to-03:00 window on Fridays and Saturdays, not in 'the weekend' as a whole.",
    evidence={"window_before_pct": pct(win[~win.after].cancelled.mean()), "window_after_pct": pct(win[win.after].cancelled.mean()),
              "rest_before_pct": pct(rest[~rest.after].cancelled.mean()), "rest_after_pct": pct(rest[rest.after].cancelled.mean()),
              "window_share_of_trips_pct": pct(len(win) / len(t)),
              "extra_cancels_window": round(extra_cancels(win)), "extra_cancels_fri_sun": round(extra_cancels(fri_sun))},
    caveat="Eight weeks only; one policy change and one hiring drive both start in week 5.",
    figure="figures/f1_when.png", action="Report the window, not the weekend."))
print("F1", findings[-1].evidence)

bands = pd.cut(t["surge_multiplier"], [0.9, 1.1, 1.3, 1.6, 2.1, 2.6, 3.1], labels=["1.0", "1.2", "1.5", "2.0", "2.5", "3.0"])
by_band = t.groupby(bands, observed=True).rider_cx.agg(["mean", "size"])
hi = t[t.surge_multiplier >= 2]
share = win.assign(hi=win.surge_multiplier >= 2).groupby("week").hi.mean() * 100
fig, (a1, a2) = plt.subplots(1, 2, figsize=(13, 4.5))
sns.barplot(x=by_band.index.astype(str), y=by_band["mean"] * 100, color="#4C78A8", ax=a1)
a1.set_xlabel("surge multiplier"); a1.set_ylabel("rider cancel rate (%)")
sns.lineplot(x=share.index, y=share.values, marker="o", color="#E45756", ax=a2)
a2.set_xlabel("week"); a2.set_ylabel("trips at surge 2.0+ (%)"); a2.set_title("Fri/Sat 22:00-03:00 window", fontsize=13); a2.axvline(4.5, ls="--", color="grey")
fig.tight_layout(); fig.savefig(FIG / "f2_surge.png", dpi=110); plt.close(fig)
findings.append(Finding(id=2, question="Did riders become less patient, or did more of them meet a high surge?",
    finding="Riders barely changed: at surge 2.0+ they cancel about the same share before and after. What changed is how many trips got surge 2.0+.",
    evidence={"rate_surge_1.0_pct": pct(by_band["mean"].iloc[0]), "rate_surge_3.0_pct": pct(by_band["mean"].iloc[-1]),
              "hi_surge_cancel_before_pct": pct(hi[~hi.after].rider_cx.mean()), "hi_surge_cancel_after_pct": pct(hi[hi.after].rider_cx.mean()),
              "night_hi_surge_share_wk1_pct": round(float(share.loc[1]), 1), "night_hi_surge_share_wk8_pct": round(float(share.loc[8]), 1)},
    caveat="Shows association inside this export; it cannot prove surge caused the cancels (no experiment).",
    figure="figures/f2_surge.png", action="Review the week-5 surge rules for the Fri/Sat night window."))
print("F2", findings[-1].evidence)

# ── chunk 3: findings 3 and 4 -- WHERE and WHO (cleaned cities, merged drivers) ──
by_city = t.groupby("city").agg(trips=("trip_id", "size"), driver_cx=("driver_cx", "mean"), eta=("pickup_eta_min", "mean"))
fig, ax = plt.subplots(figsize=(8, 4.5))
sns.barplot(x=by_city.index, y=by_city["driver_cx"] * 100, color="#59A14F", ax=ax)
ax.set_ylabel("driver cancel rate (%)"); ax.set_xlabel("")
fig.tight_layout(); fig.savefig(FIG / "f3_city.png", dpi=110); plt.close(fig)
findings.append(Finding(id=3, question="Which city is the problem once the spellings are fixed?",
    finding="Hyderabad is the second-biggest city, not a footnote, and its drivers cancel most because pickups take longest.",
    evidence={"hyderabad_trips": float(by_city.loc["Hyderabad", "trips"]), "hyderabad_driver_cx_pct": pct(by_city.loc["Hyderabad", "driver_cx"]),
              "others_driver_cx_pct": pct(by_city.drop("Hyderabad").driver_cx.mean()),
              "hyderabad_mean_eta_min": round(float(by_city.loc["Hyderabad", "eta"]), 1),
              "others_mean_eta_min": round(float(by_city.drop("Hyderabad").eta.mean()), 1)},
    caveat="ETA is the quoted wait, not the measured one; a city average hides local hotspots.",
    figure="figures/f3_city.png", action="Add supply or relax pickup radius in Hyderabad."))
print("F3", findings[-1].evidence)

known = t.dropna(subset=["driver_tenure_days"]).copy()
known["tenure"] = pd.cut(known.driver_tenure_days, [-1, 29, 89, 5000], labels=["under 30 d", "30-89 d", "90+ d"])
by_ten = known.groupby("tenure", observed=True).driver_cx.agg(["mean", "size"])
rook_share = known.assign(r=known.driver_tenure_days < 30).groupby(["fri_sat_night", "after"]).r.mean() * 100
fig, ax = plt.subplots(figsize=(8, 4.5))
sns.barplot(x=by_ten.index.astype(str), y=by_ten["mean"] * 100, color="#F28E2B", ax=ax)
ax.set_ylabel("driver cancel rate (%)"); ax.set_xlabel("driver tenure on trip day")
fig.tight_layout(); fig.savefig(FIG / "f4_rookies.png", dpi=110); plt.close(fig)
findings.append(Finding(id=4, question="Do new drivers cancel more, and are there more of them at the bad hours?",
    finding="Drivers under 30 days old cancel about three times as often, and they now cover about one in five Fri/Sat-night trips.",
    evidence={"rookie_cx_pct": pct(by_ten.loc["under 30 d", "mean"]), "veteran_cx_pct": pct(by_ten.loc["90+ d", "mean"]),
              "rookie_share_window_before_pct": round(float(rook_share.loc[(True, False)]), 1),
              "rookie_share_window_after_pct": round(float(rook_share.loc[(True, True)]), 1)},
    caveat="Rows with no driver_id (riders who cancelled before a match) are excluded; tenure and hiring date overlap.",
    figure="figures/f4_rookies.png", action="Pair rookies with short pickups at night."))
print("F4", findings[-1].evidence)

# ── chunk 4: finding 5 -- the average that lies (Simpson's paradox) ──
t["daypart"] = pd.Series(["night" if (h >= 22 or h < 5) else "day" for h in t.hour], index=t.index)
overall = t.groupby("vehicle_type").cancelled.mean() * 100
split = t.groupby(["daypart", "vehicle_type"]).cancelled.mean().unstack() * 100
mix = t.groupby("vehicle_type").daypart.apply(lambda s: (s == "night").mean() * 100)
fig, ax = plt.subplots(figsize=(8, 4.5))
plot_df = split.stack().rename("rate").reset_index()
sns.barplot(data=plot_df, x="daypart", y="rate", hue="vehicle_type", ax=ax)
ax.set_ylabel("cancel rate (%)"); ax.set_xlabel("")
fig.tight_layout(); fig.savefig(FIG / "f5_simpson.png", dpi=110); plt.close(fig)
findings.append(Finding(id=5, question="Are sedans worse than autos for cancellations?",
    finding="Overall sedans cancel more, but inside both day and night they cancel less; they simply run at night.",
    evidence={"sedan_overall_pct": round(float(overall["sedan"]), 1), "auto_overall_pct": round(float(overall["auto"]), 1),
              "sedan_day_pct": round(float(split.loc["day", "sedan"]), 1), "auto_day_pct": round(float(split.loc["day", "auto"]), 1),
              "sedan_night_pct": round(float(split.loc["night", "sedan"]), 1), "auto_night_pct": round(float(split.loc["night", "auto"]), 1),
              "sedan_night_trip_share_pct": round(float(mix["sedan"]), 1), "auto_night_trip_share_pct": round(float(mix["auto"]), 1)},
    caveat="Two day-parts are a coarse split; a third hidden factor could still remain.",
    figure="figures/f5_simpson.png", action="Do not re-price sedans on the overall number."))
print("F5", findings[-1].evidence)

# ── chunk 5: save the findings as validated JSON ──
report = Report(rows_analysed=len(t), findings=findings)           # validation runs here; bad data raises
(HERE / "findings.json").write_text(report.model_dump_json(indent=2))
again = Report.model_validate_json((HERE / "findings.json").read_text())   # a consumer re-checks on the way in
print(f"wrote findings.json: {len(again.findings)} findings, {again.rows_analysed:,} rows; schema has", len(Report.model_json_schema()["$defs"]["Finding"]["properties"]), "fields per finding")

Read the output. The seven printed lines are the summary, the five findings and the save message. Each finding line carries the numbers a person would check: percentages, trip counts and the extra-cancellation counts. The final line says five findings were written and read back, 49,000 rows analysed. If the evidence for a finding had been missing a number, Pydantic would have refused the report instead of saving something half-true.

What Priya tells Marcus

The five findings together are an answer with a shape. The table puts them in the order Marcus will hear them, with the caveat that goes with each and the action it suggests.

The five findings, each with its caveat and the action it supports
#FindingCaveatAction
1The jump is the Fri/Sat 22:00-03:00 window: 15.9% to 25.2%. The rest of the week did not move (9.1%).Eight weeks only; surge rules and a hiring drive both start in week 5.Report the window, not the weekend.
2Riders cancel the same way per surge level. The share of window trips at surge 2.0+ rose from about 15% to about 59%.Association, not an experiment.Review the week-5 surge rules for that window.
3Hyderabad is the second-largest city; its drivers cancel 3.2% against about 2.2% elsewhere, with longer pickups.Quoted wait, not measured wait.Add supply or widen pickup radius there.
4Drivers under 30 days old cancel 8.5% of trips (veterans 2.3%) and went from 1.6% to 19.2% of window trips.Hiring date overlaps the surge change.Pair new drivers with short pickups at night.
5Sedans look worse overall (13.3% vs 9.9%) but are better by day and by night; they run mostly at night.Two day-parts are a coarse split.Do not re-price sedans on the overall number.

One honest line goes at the top of her note: findings 2 and 4 both start in week 5, so this data cannot separate "the surge rules did it" from "the new drivers did it". The cleanest way to find out is a small experiment, such as capping surge in one city for two weekends. That is what a finding with a caveat is for: it ends in a next step.

Quick reference — the five findings

Finding 1
When: Fri/Sat 22:00-03:00, 15.9% to 25.2%. 284 of about 290 extra cancels.
Finding 2
Why (rider side): surge 2.0+ share 15% to 59%; per-surge behaviour unchanged.
Finding 3
Where: Hyderabad, 3.2% driver cancel, 9.2-minute pickups.
Finding 4
Who: drivers under 30 days, 8.5% against 2.3%, 19.2% of window trips.
Finding 5
The false lead: sedans, a mix effect (Simpson's paradox).
Always
One figure, one sentence with numbers, one caveat, one action.

07 · Findings as JSONHand Over Something a Program Can Trust

Wednesday evening. Priya's note for Marcus is done, but two other people want the findings. The finance analyst wants them in a dashboard. The CTO asks whether an LLM could draft the board summary from them. Both need the same thing: not a paragraph and a screenshot, but five records with the same fields every time, checked before anyone reads them.

Structured output means saving results as JSON with a fixed shape that a program can check. Without it, the next reader, human or LLM, has to guess what each field means and whether it is even there.

Pydantic is a library you may not have used. The first example below is five lines long, and nothing after it needs more than what it shows.

The smallest model

JSON is text that holds nested lists and key-value pairs, and almost every API speaks it. Pydantic (version 2) is a Python library that lets you describe the shape of such data as a class, then checks any incoming data against that class. You write the rule once, and it is enforced everywhere.

Step-by-step: what tiny_pydantic.py does, in plain English
  1. class Fare(BaseModel) declares a record with two fields: trip_id is text and fare_inr is a decimal number.
  2. Field(gt=0) adds a rule: the fare must be greater than zero.
  3. The first call passes the text "120.5". Pydantic converts it to the number 120.5 and accepts the record.
  4. The second call passes -30, which breaks the rule. Pydantic raises a ValidationError.
  5. The program catches the error and prints which field failed and why.
tiny_pydantic.pyruns offline
# tiny_pydantic.py -- the smallest Pydantic model: one rule, one pass, one fail.
# pip install "pydantic>=2.7,<3"
from pydantic import BaseModel, Field, ValidationError


class Fare(BaseModel):
    trip_id: str
    fare_inr: float = Field(gt=0)            # a fare must be above zero


print(Fare(trip_id="T1", fare_inr="120.5"))   # the text "120.5" is converted to a number
try:
    Fare(trip_id="T2", fare_inr=-30)
except ValidationError as err:
    print(err.errors()[0]["loc"], "->", err.errors()[0]["msg"])
what it printed
trip_id='T1' fare_inr=120.5
('fare_inr',) -> Input should be greater than 0

Read the output. The first line is the accepted record with fare_inr=120.5, now a number, though we passed text. The second line names the field, fare_inr, and the reason, "Input should be greater than 0". This is the cleaning idea from earlier turned into a reusable gate: the rule "a fare must be above zero" is written once and enforced on every record.

A gate with four kinds of rule

The real Finding record has more rules than a fare. The next program rebuilds a slim version and feeds it one good and one bad record, so you can see the refusal message in full. It also prints the JSON Schema Pydantic generates, which is the part that matters for LLMs.

Step-by-step: what pydantic_rejects.py does, in plain English
  1. Declare Finding with four rules: id from 1 to 5, a finding text of at least 20 characters, evidence as a dictionary of numbers, and a caveat of at least 10 characters.
  2. Validate a good dictionary with model_validate; print it back as JSON.
  3. Validate a bad dictionary that breaks four rules at once, inside try.
  4. On ValidationError, loop over err.errors() and print each field path and message.
  5. Print the JSON Schema for the id field.
pydantic_rejects.pyruns offline
# pydantic_rejects.py -- the same validation a finding gets, shown rejecting bad data, plus the JSON Schema.
# pip install "pydantic>=2.7,<3"
import json

from pydantic import BaseModel, Field, ValidationError


class Finding(BaseModel):
    id: int = Field(ge=1, le=5)
    finding: str = Field(min_length=20)
    evidence: dict[str, float]
    caveat: str = Field(min_length=10)


good = {"id": 1, "finding": "The jump lives in one 5-hour window.", "evidence": {"before_pct": 15.9}, "caveat": "Eight weeks only."}
print("accepted:", Finding.model_validate(good).model_dump_json())

bad = {"id": 7, "finding": "too short", "evidence": {"before_pct": "high"}}
try:
    Finding.model_validate(bad)
except ValidationError as err:
    print(f"rejected with {err.error_count()} problems:")
    for e in err.errors():
        print(" ", ".".join(str(p) for p in e["loc"]), "->", e["msg"])

# this exact schema is what an LLM provider is handed when you ask for structured output (module 06)
print(json.dumps(Finding.model_json_schema()["properties"]["id"]))
what it printed
accepted: {"id":1,"finding":"The jump lives in one 5-hour window.","evidence":{"before_pct":15.9},"caveat":"Eight weeks only."}
rejected with 4 problems:
  id -> Input should be less than or equal to 5
  finding -> String should have at least 20 characters
  evidence.before_pct -> Input should be a valid number, unable to parse string as a number
  caveat -> Field required
{"maximum": 5, "minimum": 1, "title": "Id", "type": "integer"}
bad record id: 7 finding: "too short" evidence: {"x": "high"} caveat: (missing) good record id: 1 evidence: {"before_pct": 15.9} Pydantic model id 1..5, text lengths, numbers are numbers rejected: 4 problems id: must be <= 5 finding: 20+ characters evidence: not a number caveat: required accepted: saved 1 2 3 4 the same schema is what an LLM is asked to follow in module 06
Fig. 7.1 — Pydantic is a gate for data: a record either satisfies the declared shape, or it is refused with a list of exactly what is wrong.
  1. Untrusted input. A dictionary from anywhere: a file, a web form, an LLM's reply. The one on top breaks four rules at once.
  2. The model. A Python class that states each field's type and limits: id between 1 and 5, finding at least 20 characters, evidence a dictionary of numbers, caveat required.
  3. Refusal with reasons. pydantic_rejects.py printed all four problems in one go, by field name. A silent default would have let the damage travel on.
  4. Accepted. The good record becomes JSON text, and the same class can read it back later, so both sides of a file or an API agree.

Read the output. The good record is accepted and printed as compact JSON. The bad record is rejected with four problems at once, each named by field: id is above 5, finding is too short, evidence.before_pct is text where a number is needed, and caveat is missing. The last line is a JSON Schema fragment, the machine-readable version of the same rules. Fig. 7.1 shows the whole flow.

Here is the beginning of the real file that eda_report.py wrote. Every finding has the same keys, the evidence is all numbers, and the caveat is present, because the gate would not let the file exist otherwise.

findings.json (first 22 lines)
{
  "rows_analysed": 49000,
  "findings": [
    {
      "id": 1,
      "question": "When exactly did cancellations jump?",
      "finding": "The jump lives in the 22:00-to-03:00 window on Fridays and Saturdays, not in 'the weekend' as a whole.",
      "evidence": {
        "window_before_pct": 15.9,
        "window_after_pct": 25.2,
        "rest_before_pct": 9.1,
        "rest_after_pct": 9.1,
        "window_share_of_trips_pct": 12.0,
        "extra_cancels_window": 284.0,
        "extra_cancels_fri_sun": 290.0
      },
      "caveat": "Eight weeks only; one policy change and one hiring drive both start in week 5.",
      "figure": "figures/f1_when.png",
      "action": "Report the window, not the weekend."
    },
    {
      "id": 2,

The tie to LLMs: why this is the same idea as structured outputs

When you ask a language model for structured output in Module 06, you do the same two things. You hand the provider a JSON Schema, and you validate what comes back. The Anthropic and OpenAI SDKs can take a Pydantic class directly and produce the schema for you. The model's reply is then parsed into your class, or rejected with a list of what is wrong.

So the habit you just practised, writing the shape of the answer first and refusing anything that does not fit, is the whole discipline of reliable LLM output. A model that replies with "caveat": null fails the same gate as a hand-written dictionary. The CTO's question has a concrete answer: yes, an LLM could draft the summary, and you would give it these five records as input and a schema as output.

Quick reference — structured JSON with Pydantic v2

BaseModel
A class whose attributes are typed fields. Creating an instance validates it.
Field(...)
Adds limits: gt, ge, le, min_length, max_length (the length limits work on lists too).
model_validate / model_validate_json
Check a dictionary or a JSON string against the class.
model_dump_json
Turn a valid record into JSON text.
ValidationError
Lists every broken rule with its field path, not only the first.
model_json_schema
The JSON Schema that LLM providers accept for structured output.
Honest limit
Pydantic checks shape and limits, not truth. A record with a wrong but well-formed number passes.

08 · The stack, and whyTools, Rivals and When to Switch

Thursday morning, before the board. Marcus's data lead, Ravi, reads Priya's scripts and asks the question every reviewer asks: "why pandas, why CSV in and Parquet out, why not Polars or SQL?" Priya has a measured answer for one of those, and a rule of thumb for the rest.

A tool is a choice, and a choice has rivals and a point where it stops being the right one. This section names them so you can defend the stack in an interview, and change it when your data changes.

The numbers that exist are from the program below, which writes the clean table as CSV and Parquet, times a read of each, and asks the same question in pandas and in DuckDB SQL. Module 01 already used DuckDB lightly; this is the same engine over the same RideNow file.

Step-by-step: what csv_vs_parquet.py does, in plain English
  1. Read the clean Parquet table, and write it back out as CSV.
  2. Print both file sizes in megabytes.
  3. Time a full CSV read, and time reading only two columns from the Parquet file.
  4. Compute the cancel rate per city in pandas, with groupby.
  5. Compute the same in DuckDB SQL, reading the Parquet file directly with no loading step.
  6. Print both answers so you can compare them.
csv_vs_parquet.pyruns offline
# csv_vs_parquet.py -- same table, two formats, three engines (pandas, DuckDB SQL), measured.
# pip install "pandas>=3,<4" "pyarrow>=20" "duckdb>=1.1"   (needs data/trips_clean.parquet)
import time
from pathlib import Path

import duckdb
import pandas as pd

data = Path(__file__).parent / "data"
trips = pd.read_parquet(data / "trips_clean.parquet")
trips.to_csv(data / "trips_clean.csv", index=False)
print(f"CSV {(data / 'trips_clean.csv').stat().st_size / 1e6:.1f} MB | Parquet {(data / 'trips_clean.parquet').stat().st_size / 1e6:.1f} MB")

t0 = time.perf_counter(); pd.read_csv(data / "trips_clean.csv"); csv_s = time.perf_counter() - t0
t0 = time.perf_counter(); pd.read_parquet(data / "trips_clean.parquet", columns=["city", "status"]); pq_s = time.perf_counter() - t0
print(f"read whole CSV {csv_s*1000:.0f} ms | read 2 Parquet columns {pq_s*1000:.0f} ms")

# the same question in pandas and in SQL
p = trips.groupby("city")["status"].apply(lambda s: round((s != "completed").mean() * 100, 1)).sort_index()
q = duckdb.sql(f"""SELECT city, round(100 * avg((status <> 'completed')::int), 1) AS cancel_pct
                   FROM '{data / 'trips_clean.parquet'}' GROUP BY city ORDER BY city""").df()
print("pandas:", p.to_dict())
print("duckdb:", dict(zip(q["city"], q["cancel_pct"])))
what it printed
CSV 6.7 MB | Parquet 1.6 MB
read whole CSV 131 ms | read 2 Parquet columns 6 ms
pandas: {'Bengaluru': 10.2, 'Chennai': 10.1, 'Hyderabad': 12.0, 'Mumbai': 10.1, 'Pune': 9.8}
duckdb: {'Bengaluru': 10.2, 'Chennai': 10.1, 'Hyderabad': 12.0, 'Mumbai': 10.1, 'Pune': 9.8}

Read the output. The same 49,000 rows take 6.7 MB as CSV and 1.6 MB as Parquet. Reading all of the CSV took about 130 milliseconds, and reading two Parquet columns took 6, because Parquet stores each column separately and skips the rest. The two engines return the identical per-city rates, with Hyderabad highest at 12.0% overall cancellations. At this size the choice is about habit and ecosystem, not speed.

The stack, and why

The one question that decides it: how big is the data compared with one machine's memory, and who else has to read the result?

What this chapter uses, what else you could use, and when to switch (as of October 2026)
LayerWe useAlternativesWhy this oneSwitch when
Dataframepandas 3.0Polars; DuckDB (SQL); PySparkEvery ML library, tutorial and colleague speaks it. pandas 3 has Arrow-backed text and copy-on-write. Bad at: one core only, and the whole table must fit in memory.Polars or DuckDB when the table no longer fits in RAM, as a rule of thumb about a third of your memory (a few GB on a laptop). PySpark when it will not fit on one machine, roughly beyond hundreds of GB.
ArraysNumPy 2.5PyTorch tensors; CuPy; JAXThe base layer under pandas, scikit-learn and seaborn. Bad at: no GPU, no automatic gradients.PyTorch when you train a model (module 04) or need the GPU; CuPy when the same NumPy code must run on a GPU with no rewrite.
Plottingmatplotlib + seabornplotly; AltairStatic images that live in a repo and a slide deck, and seaborn makes statistical charts in one call. Bad at: no hover, zoom or filters.plotly when a stakeholder must hover over points or the chart lives in a web dashboard; Altair when you want a short declarative description of each chart.
Where code runsPlain .py scriptsJupyter; VS Code notebooks; marimoEvery program here is a file you can rerun top to bottom and diff in Git. Bad at: no inline plots while exploring.A notebook when you explore a new dataset and need to see each result immediately; marimo when you want notebooks that rerun reactively and stay plain Python files.
ValidationPydantic v2pandera; Great ExpectationsValidates one record, and is the same library LLM SDKs use for structured output. Bad at: slow for checking a million rows one by one.pandera when you need to validate whole DataFrame columns, such as every fare above 0 across 1 million rows; Great Expectations when a team needs scheduled checks and reports across dozens of warehouse tables.
File formatCSV in, Parquet outFeather; JSON Lines; DuckDB fileCSV is what exports give you. Parquet kept the types and was 4 times smaller (1.6 against 6.7 MB). Bad at: you cannot open Parquet in a text editor.Stay with CSV below about 10,000 rows or when a person will open it in Excel; use Parquet above about 100,000 rows or whenever types and column reads matter.

pandas, NumPy and matplotlib are the lingua franca; switch a layer only when the data or the audience outgrows it, and say which number triggered the switch.

One more tool fact worth saying out loud. DuckDB reads a Parquet file in place with a plain FROM 'file.parquet' and needs no import step. That is the bridge to the next chapter, where the same RideNow table is asked SQL questions side by side with pandas.

Quick reference — stack choices

pandas 3 vs Polars vs DuckDB
Default to pandas; DuckDB or Polars when memory is the limit; Spark beyond one machine.
NumPy vs PyTorch
NumPy for CPU arrays; PyTorch when you need gradients or a GPU.
matplotlib/seaborn vs plotly
Static for reports and repos; plotly for interactive dashboards.
CSV vs Parquet
6.7 MB against 1.6 MB here; Parquet keeps types and reads single columns fast.
Pydantic vs pandera vs Great Expectations
One record, a whole DataFrame, a scheduled warehouse check, in that order.

09 · Under the hoodThe Math, If You Want It

Thursday, an hour before the meeting. Ravi asks two last questions: where did the plus-or-minus numbers come from, and why is the array so much faster? Priya answers both on one page. Neither is needed to use the tools.

Where the plus-or-minus range comes from — optional depth

A cancel rate is an average of 1s (cancelled) and 0s (completed). Its spread shrinks as you add trips, which is what the standard error measures.

SE = √( p × (1 − p) ÷ n )

Symbol key: SE is the standard error, how far the measured rate typically lands from the true rate. p is the measured rate as a fraction, such as 0.1054. n is the number of trips. √ is the square root, × is multiply and ÷ is divide.

Worked example: for weeks 1-4, p = 0.1054 and n = 10,892. The top part is 0.1054 × 0.8946 = 0.0943. Divided by 10,892 that is 0.00000866. The square root is 0.00294. The 95% range is 1.96 × 0.00294 = 0.0058, which is the 10.54% plus or minus 0.58 points seen in the question on luck.

Why this and not another formula: p(1 − p) is largest at p = 0.5 and shrinks towards 0 and 1, so rare events have narrower absolute ranges. The √n means to halve the range you need four times the trips. That is why small heatmap cells wobble.

The gap between two independent rates has SE = √(SE₁² + SE₂²), where SE₁ and SE₂ are the two standard errors and ² means squared. Here √(0.00294² + 0.00308²) = 0.0043, so the 0.0243 gap is 5.7 of them.

Why an array is faster than a list — optional depth

A Python list of a million decimals is a million pointers to a million separate objects scattered in memory. Each object carries a type tag and a reference count. A NumPy float64 array is one block of 8,000,000 bytes: eight bytes per number, side by side.

Because the type is known once for the whole array, one compiled loop adds numbers straight from memory. Neighbouring numbers also arrive in the processor's cache together, and modern processors can add several at once in a single instruction. The measured 23 times comes from removing the per-object bookkeeping, not from cleverer arithmetic.

Broadcasting costs no extra memory for the stretched copies: NumPy reuses the same memory and steps through it with a stride of zero in the stretched direction. That is why adding a (3, 1) column to a (1, 4) row is cheap.

There are no dumb questions

If copy-on-write means every slice is a copy, isn't pandas 3 slower and hungrier for memory?
No. pandas does not copy when you slice; it shares the memory and copies only at the moment you change something. That is where the name comes from. You pay for a copy only when you write to a slice.
Why read the CSV as text and convert later, when read_csv can guess the types?
Guessing hides mistakes. A column with one stray "1.5x" is guessed as text, and a column of IDs like 007 is guessed as a number and loses its zeros. Reading as text and converting with coerce lets you count what failed.
If I blank an impossible fare, am I not just making data up by deleting it?
You are removing a value you know is false and recording that you did. The row stays, the flag stays, and the ledger says 457. Keeping a known-false number is the real fabrication.
Is a finding with a caveat a weak finding?
No, it is a finding a manager can act on safely. A finding without a caveat gets overturned the first time someone asks "what else changed that week?"
Boardroom translation

The pitch to Marcus: "The jump is one five-hour window on Friday and Saturday nights, not the whole weekend. Riders did not become less patient; far more trips met a surge of 2.0 or more starting in week 5. New drivers cancel three to four times as often and now cover a fifth of those trips. We cannot separate the two with this data, so we recommend a two-weekend surge-cap test in one city before hiring."

The ROI frame: about 285 extra cancelled trips in four weeks sit in a window that is 12% of volume. A narrow fix costs far less than city-wide hiring. The elevator version: "clean data turned a vague worry into a five-hour window and a testable cause."

10 · The labBrief the CEO From the Messy Export

LAB 01c — Clean and explore RideNow's trips; present five non-trivial findings

Mission: reproduce Priya's week on your own machine, then extend it. Generate the data with generate_trips.py, run clean_trips.py, run eda_report.py, then add a sixth question of your own and a null result. Hand in the five-plus findings as validated JSON with figures.

  • python3 generate_trips.py writes data/trips_raw.csv with 50,000 rows; running it twice produces an identical file (check with md5sum).
  • clean_trips.py prints a ledger that matches Fig. 4.2 and leaves 49,000 rows with no text-typed numbers.
  • eda_report.py writes five figures and a findings.json that Pydantic accepts. Every finding has evidence numbers and a caveat.
  • Sixth finding, a null result: test whether payment method (UPI, cash, card) changes the cancel rate. Report the three rates with their trip counts and a plus-or-minus range. The honest answer is "no meaningful difference" (10.4%, 10.6%, 10.9% in our data).
  • Measurement criterion: for every rate in your report, show its trip count, and for the headline jump compute the 95% range as in rate_noise.py.
  • The README lists three data problems you found beyond the planted ones, and what you did about each.

Stretch goal: change the seed in generate_trips.py, rerun everything, and report which of the five findings survive. A finding that disappears on a new seed was luck.

11 · Interview radarHow This Shows Up in Interviews

Interview radar

Data-handling questions grade one thing under many disguises: do you check before you trust? Each answer below can be said aloud in under a minute.

"You are given a CSV export with timestamps in several formats and time zones. How do you clean it?"

The real test Whether you know that time-zone mistakes are silent and that you must find out what each source means.

Strong answer I read everything as text first, then classify each timestamp by its shape and parse each shape with an explicit format. For text with no zone I ask the system's owner what zone it used, because the data cannot tell me. Then I convert everything to one zone, count the rows per format, and assert that no row fits none of the rules. In our RideNow export, dropping the Z from UTC rows moved the busiest hour from 19:00 to 14:00 with no error.

Land it Parse by rule, localise from knowledge, convert once, and assert that nothing was left over.

"After a merge, your totals are higher than before. What do you check?"

Strong answer I check the row counts before and after, and whether the key is unique in the right-hand table. If the right table has two rows for one key, each left row is repeated, and sums inflate. I check with duplicated() on the key, and I use the validate="m:1" argument to merge, which raises an error if the right side is not unique. I also check whether I used the right how: an inner merge shrinks the table, a left merge keeps it.

Land it Count rows before and after every merge, and let validate enforce what you believe about the keys.

"A metric got worse overall, but better in every segment. How is that possible?"

The real test Whether you know Simpson's paradox and can show it with numbers.

Strong answer The overall figure is a weighted average of the segments, and the mix of weights changed. In a toy example, sedans cancel 5% by day and 30% by night, autos 10% and 40%, so sedans are better in both halves. But 80% of sedan trips are at night and only 20% of auto trips, so sedans are 25% overall against 16%. I would compare within segments and report the mix separately.

Land it When a total disagrees with every part, look at the weights, not the rates.

"When would you not use pandas?"

The real test Vendor-agnostic judgment with a number, not a preference.

Strong answer I would not use pandas when:

  • the table does not fit in memory, in which case DuckDB or Polars can scan a file from disk;
  • the work is mostly joins and aggregations on files already in a warehouse, where SQL is clearer;
  • the data is beyond one machine, where Spark is the usual step.

Below a few gigabytes pandas is the default because every other library takes its frames.

Land it pandas by default, and a named size or workload that triggers the switch.

"How do you get reliable structured data out of an LLM?"

The real test Whether you treat model output as untrusted input.

Strong answer I define the shape as a Pydantic model, pass its JSON Schema to the provider's structured-output feature, and validate the reply with the same model. If validation fails I retry with the error message, or fail loudly, and never pass unchecked text downstream. It is the same gate I use on any untrusted data, as in our findings file, where a missing caveat is refused.

Land it One model defines the schema and checks the reply, so the two cannot drift apart.

"Half your driver ids are missing. Do you drop those rows?"

Strong answer Not before I ask why they are missing. In our data, 55% of rider cancellations had no driver because the rider cancelled before a match, and under 1% of completed trips did. Dropping those rows would have removed most of the cancellations I was studying. I keep the row and add a no_driver flag.

Land it Missingness that depends on the outcome is information; keep it as a flag, never delete it away.

12 · RecapWhat You Can Do Now

  • You can use NumPy arrays and explain, with a measured speed-up, why they beat loops, and predict a result's shape under broadcasting.
  • You can pick the right dtype and recognise an overflow when a total looks absurd.
  • You can use pandas 3: loc and iloc, groupby with named aggregation, merge, pivot, and the two new defaults (the str dtype and always-on copy-on-write).
  • You can run a five-step cleaning checklist, count every fix, and justify drop, blank, fill or flag for each gap.
  • You can parse mixed timestamp formats and zones into one clock, and say why the lazy parse is wrong.
  • You can run the EDA loop (question, plot, finding, caveat) and choose the plot that fits the question.
  • You can spot Simpson's paradox and test whether a gap is bigger than luck.
  • You can save findings as Pydantic-validated JSON, and explain how that is the same idea as an LLM's structured output.
🧠 Flex your memory

This module: without looking, list the five cleaning steps in order and say why duplicates come after timestamps. Then say, for each of the five RideNow findings, which plot you would use.

From an earlier module: Module 01b taught that a mean can hide the shape of the data. Which number in this chapter's cleaning ledger shows that lesson most plainly, and what were its two values?

Reveal the hints

Order: types, spellings, duplicates, impossible values, missing values. Duplicates come after timestamps because two copies can differ only in how the time was written. Plots: heatmap, bar plus line, bar, bar, grouped bar. The 01b number: the mean distance, 19.8 km before cleaning and 6.7 km after.