Sub topic 3
Measuring the speedup and verifying results
This chapter assumes you can write a pandas column expression and a row loop, and that you know what timeit is. You will learn a repeatable way to check that a vectorised rewrite is correct and faster. Do both checks before you replace any loop in real code.
Check correctness first
A fast rewrite that returns different numbers is a bug. Run the loop and the column version on the same data and compare them before you time anything.
Two comparison tools cover most cases:
Series.equals(other)returns oneTrueorFalse. It requires the same index, values and dtype. TwoNaNvalues in the same position count as equal.pd.testing.assert_series_equal(a, b)raises an error that says what differs. By default it compares floats with a small tolerance, so it suits float results better thanequals.
Always compare the index as well as the values. A rewrite that returns the right numbers in the wrong row order is still wrong.
Time both versions
timeit.timeit(func, number=N) runs func N times and returns the total seconds. Pass a function, so the timing covers only the work you care about.
import timeit
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame({
"price": rng.uniform(1, 100, size=10_000),
"qty": rng.integers(1, 10, size=10_000),
})
def with_loop(frame):
out = []
for _, row in frame.iterrows():
out.append(row["price"] * row["qty"])
return pd.Series(out, index=frame.index)
def with_columns(frame):
return frame["price"] * frame["qty"]
# Verify first: the comparison is only fair if both do equivalent work.
pd.testing.assert_series_equal(
with_loop(df), with_columns(df), check_names=False
)
loop_s = timeit.timeit(lambda: with_loop(df), number=5)
cols_s = timeit.timeit(lambda: with_columns(df), number=5)
print(f"loop: {loop_s:.4f} s")
print(f"columns: {cols_s:.4f} s")
print(f"speedup: {loop_s / cols_s:.0f}x")The check_names=False argument is needed because with_loop builds an unnamed Series. In the original three-row example, both versions return an unnamed Series, so equals works there.
Your absolute times will differ from anyone else's. The ratio between the two versions is the useful number.
Common measurement errors
- Timing a tiny frame. With 3 rows, fixed overhead dominates and the vectorised version may look no faster. Use a size close to your real data.
- Timing one run. A single run is noisy. Use
number=greater than 1, and run the whole measurement more than once if the numbers vary. - Comparing unequal work. If one version also builds a DataFrame, or copies data, and the other does not, the timings are not comparable.
- Skipping the check. Put the assertion before the timing, so a wrong result stops the script.
What to record
Keep the loop version, the vectorised version and the assertion together in a test or a notebook cell. When someone later changes the vectorised code, the assertion shows whether the behaviour changed.
Exercise
Your vectorised version returns the same values as the loop, but Series.equals returns False. Name two likely causes and the tool you would use to see the difference.
Show answer
Likely causes are a different dtype (for example int64 versus float64) and a different index or row order. Use pd.testing.assertseriesequal, which raises an error that names the mismatch, and check the index, dtype and name of both results.
Exercise
Why should the equality check run before the timing code?
Show answer
A faster version that gives different results is not a valid replacement. Checking first confirms that both versions do equivalent work, so the timing compares like with like.