Sub topic 5
Vectorizing arithmetic and conditions
This chapter assumes you can write Python functions and list comprehensions, select and filter pandas columns, and know that NumPy arrays support element-wise operations. You should also have seen why row-wise loops are slow, which the previous chapter covered. Here you replace those loops with whole-column operations and learn where vectorization stops being a simple swap.
What "vectorized" means
A vectorized operation applies one instruction to a whole column. pandas hands the column to NumPy, and NumPy runs a loop written in compiled C over a contiguous block of memory. The Python interpreter is involved once for the whole column, not once per row.
A row loop pays several costs per row: building a Python object for the row, looking up values by label, running bytecode, and boxing the result. Vectorized code pays those costs once and then does only the arithmetic. This is why the gap between the two grows with the number of rows.
The example below builds on the timing approach from earlier chapters. It runs both versions on the same data.
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")On typical hardware the loop takes tens to hundreds of milliseconds and the vectorized line takes about a millisecond. Your numbers will differ. The ratio, often 50x or more, is what matters.
Replacing iterrows with column expressions
The most common slow pattern is looping with iterrows and writing results back with .loc. Each pass builds a Series and then performs a label-based assignment, which is costly on its own.
# 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 vectorized line also does the right thing with the new column. pandas aligns the two operands on their index, multiplies them element by element, and assigns the result as a new column in one step.
Operators that work on whole columns
Most arithmetic you write for a single number works unchanged on a Series:
- Arithmetic:
+,-,*,/,//,%,**. - Comparisons:
==,!=,<,<=,>,>=. These return a Boolean Series. - Logic:
&,|,~. These combine Boolean Series. - NumPy functions:
np.log,np.sqrt,np.exp,np.abs,np.clip, and so on. - Series methods:
.clip(),.abs(),.round(),.cumsum(),.shift(),.diff(),.rank().
A scalar on one side is broadcast across the column. df["total"] * 1.2 multiplies every value by 1.2 without any loop.
Conditions: from if/else to np.where
A per-row if/else is the second common reason people write loops. The vectorized equivalent builds a Boolean mask for the whole column and then picks between two values.
import numpy as np
df["discount"] = np.where(df["qty"] >= 5, 0.10, 0.0)
df["net"] = df["total"] * (1 - df["discount"])np.where(condition, value_if_true, value_if_false) evaluates the condition for every row at once. The two value arguments can be scalars, arrays, or Series, so you can choose between two columns as well as two constants.
The logic is the same as the loop version, but the structure is different:
More than two outcomes
Nested np.where calls work but become hard to read. For three or more branches, use np.select, which takes a list of conditions and a list of results. The first matching condition 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)Order matters here. Because the first match wins, the stricter condition (>= 8) must come first. If you reversed the list, no row would ever receive 0.20.
Combining conditions
Python's and, or, and not do not work on Series. They try to turn the whole Series into one truth value and raise ValueError: The truth value of a Series is ambiguous. Use &, |, and ~ instead, and wrap each comparison in parentheses, because & binds more tightly than >= or ==.
# Wrong: raises ValueError
# mask = df["qty"] >= 5 and df["price"] > 0.5
# Right
mask = (df["qty"] >= 5) & (df["price"] > 0.5)
df["flag"] = np.where(mask, "bulk-premium", "other")A common edge case is a missing value. Any comparison with NaN is False, so np.where(df["x"] > 0, ...) sends missing rows to the "false" branch. If that is wrong for your data, add an explicit test with df["x"].isna() as the first condition in np.select.
Using masks to update part of a column
np.where creates a full new column. When you only want to change the rows that match a condition, use .loc with a mask. This is still vectorized, because the mask selects all matching rows at once.
df.loc[df["qty"] == 1, "price"] = df["price"] * 1.05The right side is aligned on the index, so the assigned values line up with the selected rows. Use Series.where(cond, other) and Series.mask(cond, other) when you want to keep the original value in one case: where keeps values where the condition is true, and mask replaces them.
df["price_capped"] = df["price"].where(df["price"] <= 0.9, 0.9)For simple limits like this one, df["price"].clip(upper=0.9) is shorter and says the intent directly.
Prove the swap is safe
Rewriting a loop changes code that was producing answers you may already trust. Before deleting the old version, check that both give the same result. The next chapter covers this in depth. The short form uses pd.testing.assert_series_equal:
import pandas as pd
slow = df["total"].apply(lambda x: x * 1.2)
fast = df["total"] * 1.2
pd.testing.assert_series_equal(slow, fast)The function raises an AssertionError that describes the first difference, and it also compares dtype, index, and name. Floating-point results from different operation orders can differ in the last digits. assert_series_equal uses a small tolerance by default for floats, so ordinary rounding noise passes.
Gotchas and failure modes
Vectorized does not always mean faster
Vectorized code creates temporary arrays. An expression such as a * b + c * d - e allocates an intermediate result for each operator. On very large columns that costs memory and cache efficiency. A later chapter on eval and Numba shows how to avoid those temporaries. For columns of a few hundred thousand rows, the temporaries rarely matter.
For tiny frames, the fixed overhead of pandas (index alignment, dtype checks) can exceed the loop cost. With 50 rows you will not see a benefit and should not chase one.
Object columns fall back to Python
A column with dtype object holds Python objects, usually strings. Operations on it often run a Python-level loop internally, even though the call looks vectorized. If df["x"].dtype shows object where you expected numbers, convert it with pd.to_numeric before doing arithmetic. Check dtypes first when a "vectorized" line is slower than expected.
Index alignment can surprise you
Arithmetic between two Series aligns them on their index labels, not by position. If the indexes differ, unmatched labels produce NaN. This happens often after a filter or a sort.
a = pd.Series([1, 2, 3], index=[0, 1, 2])
b = pd.Series([10, 20, 30], index=[2, 1, 0])
print(a + b) # aligned by label: 31, 22, 13
print(a.to_numpy() + b.to_numpy()) # by position: 11, 22, 33Both results are valid, but they answer different questions. Know which one your code needs. Pass .to_numpy() when you want positional behavior, and expect a small speed gain because alignment is skipped.
Chained assignment and copies
Filtering and then assigning, as in df[df["qty"] > 5]["price"] = 0, modifies a temporary copy and leaves df unchanged. Pandas may warn about this. Use a single .loc[mask, "price"] = 0 call instead.
Loops that are legitimately hard to vectorize
Some computations depend on the previous row's result, such as a running balance that resets under a rule. Built-in methods (cumsum, shift, rolling, ewm) cover many of these. When none fits, a plain loop over NumPy arrays, or Numba, is usually better than iterrows. Reach for those only after you have tried the built-in methods.
A short checklist
- Identify the loop or
apply(axis=1)that profiling flagged. - Write the per-row logic as column expressions, with
np.whereornp.selectfor branches. - Replace
and/or/notwith&/|/~, and parenthesize each comparison. - Check dtypes and index alignment.
- Compare old and new outputs with
assert_series_equal. - Time both versions on realistic data.
Exercise
A colleague writes df["tier"] = np.where(df["qty"] >= 8, "gold", np.where(df["qty"] >= 5, "silver", "basic")). Rewrite it with np.select. Then state what happens to a row where qty is missing (NaN), and how you would label such rows "unknown" instead.
Show answer
Use df["tier"] = np.select([df["qty"] >= 8, df["qty"] >= 5], ["gold", "silver"], default="basic"). A NaN comparison is False, so a missing qty falls through to the default and gets "basic". To label it "unknown", put df["qty"].isna() first in the conditions list with the choice "unknown": np.select([df["qty"].isna(), df["qty"] >= 8, df["qty"] >= 5], ["unknown", "gold", "silver"], default="basic"). The isna test comes first because the first matching condition wins.
Exercise
Why does mask = df["qty"] >= 5 & df["price"] > 0.5 fail or give wrong results, and what is the correct form?
Show answer
The & operator has higher precedence than the comparison operators, so Python evaluates 5 & df["price"] first, which is not what you intend and usually raises a TypeError. Wrap each comparison in parentheses: mask = (df["qty"] >= 5) & (df["price"] > 0.5).