Sub topic 13
When a Loop Is Acceptable and What to Try Next
This chapter assumes you have read the earlier chapters on column arithmetic, groupby with transform, shift and cumulative methods, map and merge, and the costs of apply, iterrows and itertuples. You should be comfortable with Python functions, loops and dictionaries, and with NumPy arrays. By the end you should be able to decide whether a loop is justified, pick the cheapest kind of loop, and know what to reach for when a loop is too slow.
Decide before you give up on vectorising
Most loops that look unavoidable are not. Before accepting a loop, run through the techniques from earlier chapters:
- Can the logic be written as arithmetic between columns?
- Can the
if/elsebranches become a mask,numpy.whereornumpy.select? - Does the loop compute something per group? Try
groupbywithtransform. - Does each row depend on the previous row? Try
shift,diff,cumsumand the other cumulative methods. - Is the loop looking something up in a dictionary or another table? Try
mapormerge.
If all five fail, a loop is a reasonable choice. Even then, the next question is whether the loop is slow enough to matter.
Cases where a loop is acceptable
The data is small
Vectorising pays off when row counts grow. For a few hundred or a few thousand rows, the whole loop may finish in milliseconds. A clear loop that a teammate can read is often worth more than a clever one-liner that saves a few milliseconds.
The work per row is not computation
If each row triggers a network request, a database write or a file operation, the time goes to waiting on that operation. Replacing iterrows with a vectorised expression would not help, because the expression does not exist. Focus on batching requests, caching results, or running them concurrently instead.
The logic is a true recurrence
Some calculations feed each row's result into the next row in a way that cumsum and shift cannot express. A common example is a balance that can never drop below zero:
balance[t] = max(0, balance[t-1] + change[t])
The max makes the result depend on every earlier clamp, so a plain cumsum gives the wrong answer. Other examples are a filter whose state resets under a data-dependent rule, or a simulation where each step reads the previous output.
The row logic calls code you cannot vectorise
Each row might go through a third-party parser, a model that accepts one record at a time, or a function that returns objects of varying size. You can still reduce overhead by looping over plain values instead of Series objects.
Choose the least costly loop
Not all loops cost the same. The expensive part of iterrows and apply(axis=1) is building a Series for every row. The cheaper options avoid that.
| Approach | What each step receives | Relative cost | Notes |
|---|---|---|---|
| `iterrows()` | A new Series per row | Highest | Mixed columns are upcast to a common dtype, which can change values |
| `apply(func, axis=1)` | A new Series per row | High | Reads well but has the same per-row overhead as `iterrows` |
| `itertuples()` | A named tuple per row | Medium | Keeps column dtypes per field, and access is by attribute |
| `zip` over columns, or `.tolist()` | Plain Python values | Lowest of the Python loops | You must name each column yourself |
| `Series.apply(func)` on one column | One value per call | Medium | A Python call per value, but no row Series |
A loop over lists of plain values is the cheapest pure-Python option:
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 15.0], "qty": [3, 1, 4]})
totals = []
for price, qty in zip(df["price"].tolist(), df["qty"].tolist()):
totals.append(price * qty)
df["total"] = totals
print(df)Calling .tolist() converts NumPy scalars to native Python numbers, which are faster to work with in a Python loop. Zipping columns also avoids the dtype-upcasting problem of iterrows.
Build results in a list, then assign once
Two habits keep loops from becoming slower than they need to be:
- Do not grow a DataFrame row by row with
pd.concator.locinside the loop. Each step copies data, so the cost grows quadratically. Append to a list, then build the DataFrame or column once after the loop. - Do not modify the DataFrame you are iterating over. Write results to a separate list and assign after the loop ends. Changes made during iteration may not be visible to the loop and can raise warnings.
What to try when the loop is too slow
Rethink the formulation
Problems that look sequential often have a vectorised form. A streak counter is a good example. It seems to need a running counter that resets on every zero, but a group id built with cumsum handles it:
import pandas as pd
s = pd.Series([1, 1, 0, 1, 1, 1, 0])
run_id = (s != s.shift()).cumsum()
streak = s.groupby(run_id).cumsum()
print(streak.tolist())The expression s != s.shift() is True wherever the value changes, so its cumsum assigns a new id to each run of equal values. A grouped cumsum then restarts at every run. The output is [1, 2, 0, 1, 2, 3, 0]. The general pattern is to use cumsum on a change flag to create group labels, then use groupby on those labels.
Move the loop onto NumPy arrays
If the recurrence is real, loop over a NumPy array instead of a DataFrame. The loop body stays plain Python, but there are no per-row pandas objects.
Compile the loop with Numba
Numba compiles a Python function that works on NumPy arrays and numbers into machine code the first time it is called. A loop that was slow in Python then runs at near-C speed. Install it with pip install numba.
This example compares a pure-Python loop and a compiled one on the floored balance recurrence:
import numpy as np
import pandas as pd
from numba import njit
def floored_balance_py(changes):
out = []
balance = 0.0
for change in changes:
balance = max(0.0, balance + change)
out.append(balance)
return out
@njit
def floored_balance_nb(changes):
out = np.empty(changes.shape[0])
balance = 0.0
for i in range(changes.shape[0]):
balance = max(0.0, balance + changes[i])
out[i] = balance
return out
df = pd.DataFrame({"change": [5.0, -8.0, 4.0, -1.0, 6.0]})
values = df["change"].to_numpy()
df["balance"] = floored_balance_py(values.tolist())
assert np.allclose(df["balance"], floored_balance_nb(values))
print(df)The balance column is [5, 0, 4, 3, 9]. The assert follows the same rule as the earlier timing chapter: check that both versions agree before comparing speed.
Numba has limits you should know about:
- It works with NumPy arrays, numbers and a subset of Python. It does not understand DataFrames,
.straccessors or arbitrary Python objects. Pass in.to_numpy()arrays and wrap the result yourself. - The first call includes compile time. Time the second and later calls, or the benchmark will mislead you.
- It adds a dependency, and it can lag behind new Python versions. Weigh that against the speedup.
Other options
DataFrame.evalandpandas.evalcan speed up long arithmetic expressions on large frames when the optionalnumexprpackage is installed. They do not help with recurrences.- Rolling windows with custom functions use
rolling(...).apply(func, raw=True). Withraw=Truethe function receives a NumPy array instead of a Series, which is cheaper. For some cases, pandas also acceptsengine="numba"there. numpy.vectorizeis only a convenience wrapper around a Python loop. It does not give you the speed of real vectorisation.- Another dataframe library such as Polars, or a database query, may suit the job if a large part of your pipeline is slow. This is a larger change, so consider it only after the cheaper options.
Keep the replacement honest
Whichever route you take, follow the same routine from the measuring chapter:
- Keep the simple loop as a reference version.
- Check that the faster version returns the same result, using
assertwithequalsornp.allclosefor floating-point values. - Time both on data of realistic size. A speedup on 10 rows says little about 10 million.
- Add a short comment on why a loop or compiled function is used, so no one "fixes" it into something wrong.
Summary of when to use what
| Situation | Reasonable choice |
|---|---|
| Column logic, branches, group totals, lookups | Vectorise |
| Small frame, one-off script | Simple loop or `apply` |
| Per-row network or file work | Loop, with batching or concurrency |
| True recurrence on a large frame | NumPy array loop, then Numba |
| Per-row logic with plain Python values | `zip` over `.tolist()` or `itertuples` |
| Whole pipeline too slow | Consider a different engine |
Exercise
A column flag holds 0 and 1. You need a column that counts how many consecutive 1s have occurred up to each row, resetting to 0 whenever the flag is 0. A teammate says this needs a loop. Write the vectorised version, and say why it works.
Show answer
Use run_id = (df["flag"] != df["flag"].shift()).cumsum() and then df["streak"] = df["flag"].groupby(run_id).cumsum(). The comparison with the shifted column is True wherever the value changes, so its cumulative sum gives each run of equal values its own id. Grouping by that id restarts the cumulative sum at the start of each run. Within a run of 1s the sum counts 1, 2, 3, and within a run of 0s it stays at 0.
Exercise
You must clamp a running balance at zero, where each new balance is max(0, previous + change). Explain why cumsum followed by a clip does not give the right answer, and name two ways to implement it for a million rows.
Show answer
cumsum adds all changes without clamping at each step, so a negative dip never resets the balance. Clipping the final sums afterwards does not reproduce the step-by-step clamp. For example, changes of 5, -8 and 4 give balances of 5, 0 and 4, but the cumulative sums are 5, -3 and 1. Two options are a loop over a NumPy array (or .tolist()) that carries the balance, and the same loop compiled with Numba using @njit. The Numba version is the faster one for a million rows.
Exercise
Why is for price, qty in zip(df["price"].tolist(), df["qty"].tolist()) usually faster than df.iterrows(), and what is one correctness risk of iterrows that the zip version avoids?
Show answer
iterrows builds a new Series for every row, which is expensive. The zip version iterates plain Python lists, so there is no per-row pandas object. The correctness risk is dtype upcasting. A row Series has a single dtype, so a row that mixes integers and floats turns the integers into floats, and a row that mixes numbers and text becomes object. Each column in the zip version keeps its own type.