Sub topic 6
Proving the fast version gives the same answer
This chapter assumes you can write a pandas loop and its vectorized equivalent, which the previous chapters covered. It also assumes you know what a Series index and a dtype are. A faster version of your code is only useful if it returns the same result. This chapter shows how to check that before you delete the old code.
Why "it looks the same" is not enough
Printing both results and comparing the first few rows misses most differences. Typical hidden changes are:
- A different dtype, such as
int64in one result andfloat64in the other. - A different index, such as a loop result with a fresh
0..nindex and a vectorized result that kept the original labels. - Row order, which changes when a groupby sorts its keys.
- Floating-point rounding, where
0.1 + 0.2and0.3differ in the last bits. - Missing values handled differently, such as
NaNskipped by one version and propagated by the other.
Compare with pandas testing helpers
pd.testing.assert_series_equal and pd.testing.assert_frame_equal return nothing when the inputs match. When they differ, they raise an AssertionError that names what differs: values, dtype, index, or name. They treat NaN in the same position as equal, which == does not.
import pandas as pd
df = pd.DataFrame({"total": [10.0, 20.5, 31.25]})
slow = df["total"].apply(lambda x: x * 1.2)
fast = df["total"] * 1.2
pd.testing.assert_series_equal(slow, fast)
print("identical")A full before-and-after check
Put the old logic and the new logic in functions that take the same input. Then compare them on the same data.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame({
"price": rng.random(1_000),
"qty": rng.integers(1, 10, 1_000),
})
def net_slow(frame):
out = []
for row in frame.itertuples(index=False):
total = row.price * row.qty
if row.qty >= 5:
total = total * 0.9
out.append(total)
return pd.Series(out, index=frame.index, name="net")
def net_fast(frame):
total = frame["price"] * frame["qty"]
discount = np.where(frame["qty"] >= 5, 0.10, 0.0)
return (total * (1 - discount)).rename("net")
pd.testing.assert_series_equal(net_slow(df), net_fast(df))
print("net_fast matches net_slow")The index=frame.index and name="net" arguments in net_slow matter. Without them the comparison would fail even though the numbers agree, because the helper checks the index and the name too.
Floating-point tolerance
For float columns the helpers allow a small relative difference by default (rtol=1e-5). Vectorized sums can add numbers in a different order than a loop, so the last digits may differ. You can set the tolerance explicitly when you want it visible in the code:
pd.testing.assert_series_equal(net_slow(df), net_fast(df), rtol=1e-9, atol=0)Integer columns are compared exactly. Loosen a tolerance only when you understand why the results differ.
Common errors and what they mean
| Error message mentions | Likely cause | Fix |
|---|---|---|
| `Attributes of Series are different (dtype)` | One version returns `int64`, the other `float64`, or `object` versus `category` | Convert with `astype`, or pass `check_dtype=False` if the difference is acceptable |
| `Index are different` | Loop output got a new `RangeIndex`, or a groupby reordered rows | Pass `index=frame.index` when building the result, or call `sort_index()` on both |
| `Series are different` with a percentage | Real value differences | Compare the rows that differ, for example `(a - b).abs().nlargest(5)` |
| `Series name` | One result has a name and the other does not | Use `rename` to set the same name |
Test on awkward data
Random clean data can pass while real data fails. Include missing values, empty frames, duplicate index labels, and boundary values such as qty == 5 in the data you compare. If the real dataset is large, compare on a sample of a few thousand rows. The slow version is often too slow to run on everything.
Exercise
A groupby-based rewrite returns the same numbers as the old loop, but assert_series_equal fails with "Index are different". What is the most likely cause, and how do you fix it without hiding real differences?
Show answer
The two results list the group keys in different order. A groupby sorts keys by default, while the loop kept first-seen order. Call sort_index() on both results before comparing, or build the loop result in sorted key order. Keep the default check_index_type and check_dtype settings so real differences still raise errors.