Sub topic 13
When a loop is acceptable and what to try next
This chapter assumes you can write pandas column expressions, use groupby, and have timed a loop against a vectorised version with timeit. It covers how to recognise code that cannot be vectorised, and what to do when you reach one.
Signs that vectorising will not work
Most row loops can be rewritten. A few cannot, or the rewrite costs more in clarity than it saves in time. Look for these patterns:
- State that depends on earlier results in a way
shiftandcumsumcannot express. An example is a balance that is capped at a limit after every step, so each row depends on the clipped result of the row before. - Calls to code that works on one value at a time. An example is a parsing function from a library, or a web request per row.
- Branching that changes which operation runs, with different logic in each branch. If each branch is simple,
numpy.whereornumpy.selecthandles it. If each branch runs a different algorithm, it often does not. - Small data. With a few hundred rows, the loop finishes in milliseconds. Rewriting it gains nothing measurable.
Make the loop cheaper first
If you must loop, avoid iterrows. It builds a Series for every row, which is the main cost. itertuples returns lightweight named tuples and is usually several times faster.
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 15.0], "qty": [3, 1, 4]})
total = 0.0
for row in df.itertuples(index=False):
total += row.price * row.qty
print(total)Looping over plain lists is cheaper still. Pull the columns out with .to_numpy() or .tolist() and loop over those. This skips pandas objects entirely.
A stateful loop that resists vectorising
Here a running balance cannot go below zero. Each row depends on the clipped balance from the previous row, so cumsum gives the wrong answer.
import pandas as pd
moves = pd.DataFrame({"change": [5, -8, 4, -2, 6]})
balance = 0
balances = []
for change in moves["change"].to_numpy():
balance = max(0, balance + change)
balances.append(balance)
moves["balance"] = balances
print(moves)The result is 5, 0, 4, 2, 8. A plain cumsum would give 5, -3, 1, -1, 5. The loop runs over a NumPy array, not over DataFrame rows, so it is already cheap.
What to try when the loop is still too slow
Try these in order. Each adds more complexity than the one before.
- Check whether part of the logic can be vectorised. Compute everything that is column-wise first, and loop only over the stateful step.
- Use
numba. Its@njitdecorator compiles a Python loop over NumPy arrays to machine code. It suits numeric loops like the balance example. It does not accept arbitrary pandas objects, so pass in arrays. - Use a different tool. For very large data, engines such as Polars or a database query may fit better than pandas.
import numpy as np
from numba import njit
@njit
def floored_balance(changes):
out = np.empty(len(changes))
balance = 0.0
for i in range(len(changes)):
balance = max(0.0, balance + changes[i])
out[i] = balance
return out
moves["balance"] = floored_balance(moves["change"].to_numpy())Decision checklist
| Question | If yes |
|---|---|
| Do column operations, masks, `groupby` or `shift` express it? | Vectorise |
| Is it fast enough already? | Keep the loop |
| Is the loop over DataFrame rows? | Switch to `itertuples` or arrays |
| Is it numeric, stateful and still slow? | Try `numba` |
Always verify a replacement against the original output, as in the assert check from the timing chapter, and keep the readable version when the speed difference does not matter.
Exercise
A loop over 200 rows calls a function that fetches a currency rate from a web service for each row, and the whole loop takes 0.01 seconds of pandas work plus network time. Should you try to vectorise it? What would you do instead?
Show answer
No. The cost is the network call, not pandas row access, so vectorising will not help. Fetch each distinct currency once, store the rates in a dictionary, and use map to fill the column. That reduces the number of calls to the number of distinct currencies, and the rest is a vectorised lookup.
Exercise
In the balance example, why does cumsum give a different answer from the loop, and which tool would you try if the loop ran over 50 million rows?
Show answer
cumsum adds every change without applying the floor at zero after each step, so negative balances carry forward. The loop applies max(0, ...) at each row, which makes each value depend on the previous clipped value. For 50 million rows, pass the NumPy array to a numba @njit function.