Sub topic 6
Proving the fast version gives the same answer
A faster pandas function is only an improvement if it returns the same result as the old one. This chapter shows how to check that with pd.testing, how to choose tolerances for floating-point numbers, and how to build a repeatable comparison before you delete the slow code.
This chapter assumes you can read and write pandas code with Series, DataFrames, and groupby. It also assumes you have seen vectorized operations such as df["price"] * df["qty"] and np.where.
Why "looks the same" is not enough
Printing both results and comparing them by eye misses most real differences. A vectorized rewrite can change any of these without changing the numbers you glance at:
- The dtype, for example
int64becomingfloat64. - The index, including its values, its name, and its order.
- The Series name or the column order.
- How missing values are handled.
- The last few digits of a float sum.
- Whether the input frame was modified.
pd.testing.assert_series_equal and pd.testing.assert_frame_equal check all of these and raise an AssertionError that says which one differs. Because the checks are strict by default, you can tell the tool to relax a rule on purpose and say why.
The basic comparison
Start with a case that should pass. Both versions multiply by 1.2 using the same floating-point operation on each value, so the results are identical.
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),
})
df["total"] = df["price"] * df["qty"]
slow = df["total"].apply(lambda x: x * 1.2)
fast = df["total"] * 1.2
pd.testing.assert_series_equal(slow, fast)
print("identical")If the assertion passes, it returns None and the script prints identical. If it fails, you get an exception, which is what you want inside a test suite or a notebook cell.
Reading a failure
A common first failure is metadata. A list comprehension returns a plain list, and wrapping it in pd.Series gives a default index and no name.
slow = pd.Series([x * 1.2 for x in df["total"]])
fast = df["total"] * 1.2
try:
pd.testing.assert_series_equal(slow, fast)
except AssertionError as err:
print(err)The message reports that the attribute name differs: None on one side and "total" on the other. The values match, but downstream code that selects result["total"] or aligns on the index would behave differently. Fix the construction instead of silencing the check:
slow = pd.Series([x * 1.2 for x in df["total"]], index=df.index, name="total")
pd.testing.assert_series_equal(slow, fast)
print("identical")Pass check_names=False only when the name is irrelevant to every consumer of the result.
Choosing which checks to relax
The comparison functions take keyword arguments that loosen specific rules. Relax one at a time, and only for a stated reason.
| Argument | What it does | When relaxing it is reasonable |
|---|---|---|
| `check_dtype=False` | Compares values without requiring equal dtypes | You deliberately moved to a smaller dtype such as `float32` |
| `check_names=False` | Ignores Series and index names | The name is not used downstream |
| `check_exact=False` with `rtol`, `atol` | Compares floats within a tolerance | The two versions add numbers in a different order |
| `check_like=True` | Ignores the order of index labels (and columns, for frames) | Row order is not part of the result's meaning |
| `check_index_type=False` | Allows different index classes | Rarely. Prefer to fix the index |
The tolerance defaults depend on your pandas version. Float comparisons are approximate by default with rtol=1e-5, which is loose. Integer comparisons are exact in recent versions. Set rtol and atol yourself instead of relying on the defaults, and keep the values small.
Dtype changes can hide precision loss
Moving a column to float32 halves its memory but changes the values slightly. With check_dtype=False, the default tolerance accepts that difference.
original = df["price"]
smaller = df["price"].astype("float32")
try:
pd.testing.assert_series_equal(original, smaller)
except AssertionError:
print("dtype differs, as expected")
pd.testing.assert_series_equal(original, smaller, check_dtype=False)
print("values agree within the default tolerance")Passing here means the values agree to about five significant digits. If a later step needs more precision, such as a sum over millions of rows or a comparison against a threshold, pass a tighter rtol and see whether the check still passes.
Floating-point sums depend on order
Adding floats is not associative. A Python loop adds values one at a time from left to right. NumPy uses pairwise summation, which groups the additions differently. Both are valid, but they can differ in the last digits.
import math
values = rng.random(1_000_000)
naive = sum(values.tolist())
pairwise = values.sum()
exact = math.fsum(values)
print("naive == pairwise:", naive == pairwise)
print("naive error :", abs(naive - exact) / exact)
print("pairwise error:", abs(pairwise - exact) / exact)The first line usually prints False. The relative errors are tiny, around 1e-12 to 1e-16. Here the vectorized sum is typically closer to the exact value, so the "slow, known-good" result is not necessarily the more accurate one. Use a tolerance far tighter than the default, so a real bug still fails but order-of-addition noise passes:
pd.testing.assert_series_equal(
pd.Series([naive]),
pd.Series([pairwise]),
check_exact=False,
rtol=1e-9,
)
print("sums agree within 1e-9")Comparing grouped results
Group results often differ in ordering and index naming. A dictionary-based loop returns keys in first-seen order, while groupby sorts the keys by default. Normalize the order of the old result, not the new one, so you check what the new code actually returns.
def totals_slow(frame):
out = {}
for row in frame.itertuples(index=False):
out[row.qty] = out.get(row.qty, 0.0) + row.total
return pd.Series(out, name="total").rename_axis("qty")
def totals_fast(frame):
return frame.groupby("qty")["total"].sum()
expected = totals_slow(df).sort_index()
actual = totals_fast(df)
pd.testing.assert_series_equal(expected, actual, check_exact=False, rtol=1e-9)
print("group totals match")Sorting the old result with sort_index() is a deliberate decision that row order is not part of the contract. If callers do depend on first-seen order, pass sort=False to groupby instead and drop the sort_index() call.
For a DataFrame result, assert_frame_equal works the same way. check_like=True is a shortcut when only the set of labels matters, but it hides ordering bugs, so use it knowingly.
A reusable check across edge inputs
A comparison on one random frame proves little. Most rewrites break on unusual inputs: missing values, a non-default index, duplicate index labels, or an empty frame. The helper below runs both versions on several frames and also confirms that neither version modified its input.
def discount_slow(frame):
return frame["qty"].apply(lambda q: 0.10 if q >= 5 else 0.0)
def discount_fast(frame):
return pd.Series(
np.where(frame["qty"] >= 5, 0.10, 0.0),
index=frame.index,
name="qty",
)
def check_same(old_fn, new_fn, frames, **kwargs):
for label, frame in frames.items():
before = frame.copy(deep=True)
expected = old_fn(frame)
actual = new_fn(frame)
pd.testing.assert_frame_equal(frame, before)
pd.testing.assert_series_equal(expected, actual, **kwargs)
print(f"{label}: ok")
frames = {
"plain": pd.DataFrame({"qty": [1, 5, 9]}),
"with NaN": pd.DataFrame({"qty": [1.0, np.nan, 7.0]}),
"string index": pd.DataFrame({"qty": [2, 6]}, index=["a", "b"]),
"duplicate index": pd.DataFrame({"qty": [2, 6]}, index=[0, 0]),
}
check_same(discount_slow, discount_fast, frames)Each frame targets a specific risk:
- NaN.
np.nan >= 5isFalse, so both versions assign a 0.0 discount. That agreement is a decision you should confirm is the business rule. If NaN quantities should produce a NaN discount, both versions need to change. - Custom and duplicate indexes. Building the fast result with
index=frame.indexkeeps labels aligned. Forgetting it produces a defaultRangeIndexand a failure on the string-index case. - Input mutation. Comparing the frame to a deep copy catches code that quietly adds a column or edits values in place.
Also try an empty frame. The old and new versions can return different dtypes for empty input, because apply on an empty Series may keep the input dtype while np.where returns floats. Decide which dtype is correct and make both versions agree. Other cases worth adding are a single row, all rows in one group, and a column of all-identical values.
Keeping a reference when the old code is gone
You will sometimes delete the slow code in a later commit. Before you do, save its output on a fixed sample, for example with result.to_parquet("expected_totals.parquet"), and commit the file with a small input sample. A later test can read that file and call assert_frame_equal against the new function's output. Parquet preserves dtypes and index information better than CSV, which reads everything back as strings and numbers by inference and often fails a strict comparison for reasons unrelated to your code.
Common causes of mismatch
| Symptom in the assertion message | Likely cause | Typical fix |
|---|---|---|
| `Attribute "name" are different` | The Series was rebuilt without a name | Pass `name=` when you construct it |
| `Attribute "dtype" are different` | An integer column became float, or a dtype was shrunk | Cast explicitly, or relax with a comment |
| `Index are different` | New result has a default index or different order | Pass `index=frame.index`, or sort both sides |
| `values are different (0.0001 %)` | Different order of float additions | Use `check_exact=False` with a small `rtol` |
| A different number of rows | Merge or filter changed row counts | Check join keys and duplicate keys |
Summary of the habit
- Keep the old function until the comparison passes.
- Compare with
assert_series_equalorassert_frame_equalinstead of==or.equalsalone, because the assertion explains what differs. - Relax a single check at a time and write down why.
- Run the comparison on edge inputs, not only on the large benchmark frame.
- Re-run the timing after the rewrite passes, so the speedup you report belongs to the version you will actually keep.
Exercise
A colleague replaces df["qty"].apply(lambda q: q * 2) with df["qty"] * 2 and reports that assert_series_equal(slow, fast) passes. They then change fast to (df["qty"] * 2).astype("float32") and call assert_series_equal(slow, fast, check_dtype=False), which also passes. Why is the second pass weaker evidence, and what would you add to the check?
Show answer
The first call checks the dtype exactly, so it proves both versions return the same dtype and values. The second call ignores the dtype and compares values with the default float tolerance (about 1e-5 relative), so precision lost in the float32 cast can pass unnoticed. Keep the dtype change only if it is intended, compare with an explicit small rtol such as 1e-9 (which will fail if precision was lost beyond that), and also compare a downstream result such as a sum or a filtered row count between the two versions.