Sub topic 5
Vectorizing arithmetic and conditions
This chapter assumes you know basic Python, pandas DataFrames and Series, and the idea that NumPy applies operations to whole arrays at once. Earlier chapters covered timing and profiling, and why row-wise loops are slow. Here you replace those loops.
What vectorized means
A vectorized operation works on a whole column in one call. pandas passes the column's underlying NumPy array to compiled code, which loops in C. Your Python code runs once for the column instead of once per row, so it avoids the interpreter overhead that makes iterrows slow.
Arithmetic on columns
Column arithmetic is element-wise and aligned on the index. This code measures a row loop against a single expression.
import numpy as np
import pandas as pd
from time import perf_counter
rng = np.random.default_rng(0)
df = pd.DataFrame({
"price": rng.random(200_000),
"qty": rng.integers(1, 10, 200_000),
})
start = perf_counter()
totals = [row.price * row.qty for row in df.itertuples(index=False)]
print(f"itertuples loop: {perf_counter() - start:.3f}s")
start = perf_counter()
totals_vec = df["price"] * df["qty"]
print(f"vectorized: {perf_counter() - start:.3f}s")The exact numbers depend on your machine. The vectorized line is typically tens to hundreds of times faster.
The same change applies to the iterrows pattern, which also writes into the frame one cell at a time:
# Slow: one Python-level iteration per row
for i, row in df.iterrows():
df.loc[i, "total"] = row["price"] * row["qty"]
# Fast: one operation on whole columns
df["total"] = df["price"] * df["qty"]The slow version also builds a new Series for every row, and each .loc assignment is a separate indexing call.
Conditions with np.where
A per-row if/else becomes a boolean array. np.where(condition, value_if_true, value_if_false) evaluates the condition for the whole column and picks values from either branch.
import numpy as np
df["discount"] = np.where(df["qty"] >= 5, 0.10, 0.0)
df["net"] = df["total"] * (1 - df["discount"])The expression df["qty"] >= 5 produces a Series of True and False. np.where then builds the discount column in one pass.
For more than two outcomes, use np.select with a list of conditions and a list of matching values. The first condition that is true wins, and default covers rows that match none.
conditions = [df["qty"] >= 8, df["qty"] >= 5]
choices = [0.20, 0.10]
df["discount"] = np.select(conditions, choices, default=0.0)You can also combine conditions with &, |, and ~. Wrap each comparison in parentheses, because these operators bind more tightly than >= and ==.
mask = (df["qty"] >= 5) & (df["price"] > 0.5)
df["bulk_premium"] = np.where(mask, "yes", "no")Common errors
- Using
andororon Series. Python raisesValueError: The truth value of a Series is ambiguous. Use&and|instead. - Forgetting parentheses around comparisons in a combined mask.
- Calling
np.wherewith a single argument. It then returns index positions, not a column of values. - Assuming a vectorized version is always faster. On a few hundred rows, setup cost dominates and the difference is small. Measure before you rewrite.
Exercises
Exercise
A column score holds integers. Write one line that creates a column grade with "pass" where score >= 50 and "fail" otherwise, without a loop or apply.
Show answer
df["grade"] = np.where(df["score"] >= 50, "pass", "fail")
Exercise
This line raises a ValueError: df[(df["qty"] > 2) and (df["price"] < 1)]. Why does it fail, and what is the fix?
Show answer
Python's and asks for a single True or False from each Series, which is ambiguous for many values. Use the element-wise operator instead: df[(df["qty"] > 2) & (df["price"] < 1)].