Sub topic 9
Previous-row and running-total logic
This chapter assumes you can build a DataFrame, know the groupby basics, and have read the earlier chapters on column arithmetic and groupby with transform. It covers loops that carry state from one row to the next, such as "compare with the previous row" and "keep a running total". Both patterns have vectorised forms.
Why these loops look hard to vectorise
A typical row loop for this kind of logic keeps a variable outside the loop. It updates the variable on each pass:
import pandas as pd
sales = pd.DataFrame({
"store": ["a", "a", "a", "b", "b"],
"day": pd.to_datetime(
["2026-03-01", "2026-03-02", "2026-03-03", "2026-03-01", "2026-03-02"]
),
"amount": [10, 30, 20, 5, 15],
})
prev = None
running = 0
changes, totals = [], []
for row in sales.itertuples(index=False):
changes.append(None if prev is None else row.amount - prev)
running += row.amount
totals.append(running)
prev = row.amountThis version has a bug. It never resets prev or running when the store changes, so store b inherits store a's state. Fixing that means more variables, more if statements and a dictionary keyed by store.
The vectorised tools below carry state for you. They also reset it at group boundaries when you combine them with groupby.
Sort first
Every operation in this chapter depends on row order. shift looks at the row above, and cumsum adds rows from the top down. If the data is not in the order you mean, the result is wrong, and pandas will not warn you.
sales = sales.sort_values(["store", "day"]).reset_index(drop=True)Sort by the group key first and the time column second. If a loop was correct on a particular row order, the vectorised version needs that same order.
shift: looking at the previous or next row
Series.shift(n) moves values down by n positions. The index stays where it is, so each row now holds the value from n rows above. The first n rows become NaN.
sales["prev_amount"] = sales.groupby("store")["amount"].shift(1)
sales["next_amount"] = sales.groupby("store")["amount"].shift(-1)
print(sales[["store", "amount", "prev_amount", "next_amount"]])A negative n looks forward. Because the call goes through groupby("store"), the first row of store b gets NaN rather than the last amount of store a. Without the groupby, values leak across groups.
| store | amount | prev_amount | next_amount |
|---|---|---|---|
| a | 10 | NaN | 30 |
| a | 30 | 10 | 20 |
| a | 20 | 30 | NaN |
| b | 5 | NaN | 15 |
| b | 15 | 5 | NaN |
Integer columns become floats
NaN is a float value. When shift introduces missing values into an int64 column, pandas converts the result to float64. If you want to keep integers, pass a fill_value, or use a nullable dtype such as Int64:
import pandas as pd
amounts = pd.Series([10, 30, 20])
print(amounts.shift(1).dtype) # float64
print(amounts.shift(1, fill_value=0).dtype) # int64
print(amounts.astype("Int64").shift(1).dtype) # Int64A fill_value of 0 is only safe when zero means "nothing before this row" in your data. For a first-row difference, missing is often the honest answer.
diff and pct_change: the change from the previous row
diff is a shortcut for x - x.shift(1). pct_change is x / x.shift(1) - 1.
by_store = sales.groupby("store")["amount"]
sales["change"] = by_store.diff()
sales["pct_change"] = by_store.pct_change()For store a, change is NaN, 20, -10, and pct_change is NaN, 2.0, -0.33.... Both take a periods argument. For example, diff(7) compares each row with the row seven positions earlier. Rows are counted, not days. If dates are missing, seven rows back is not seven days back. For calendar-based comparisons, reindex to a full date range first or use rolling with a time window.
On datetime columns, diff returns a Timedelta. That is the key to sessionising events, shown later in this chapter.
Cumulative methods: running totals and friends
The cumulative methods cumsum, cumprod, cummax and cummin return a running result for each row. Combined with groupby, they restart for every group.
sales["running_total"] = sales.groupby("store")["amount"].cumsum()
sales["running_max"] = sales.groupby("store")["amount"].cummax()
sales["row_number"] = sales.groupby("store").cumcount()cumcount numbers the rows within each group, starting at 0. It is the vectorised replacement for a counter variable that you reset on every new key. For a running average, use expanding:
sales["running_mean"] = (
sales.groupby("store")["amount"].expanding().mean().reset_index(level=0, drop=True)
)The groupby(...).expanding() call returns a result indexed by group key and original index. reset_index(level=0, drop=True) removes the group level, so the result aligns with sales again. Without it, the assignment would try to align a two-level index and fail or produce NaN.
Missing values in cumulative methods
By default, cumsum skips NaN. A missing value stays NaN in its own position, and the running total continues from the last valid total:
import numpy as np
import pandas as pd
s = pd.Series([1.0, np.nan, 2.0])
print(s.cumsum().tolist()) # [1.0, nan, 3.0]
print(s.cumsum(skipna=False).tolist()) # [1.0, nan, nan]Decide which behaviour matches your data. If a missing value should count as zero, call fillna(0) first. If one missing value should invalidate everything after it, use skipna=False.
Flagging a change from the previous row
Comparing a column with its shifted self gives a boolean mask. That mask can drive filtering or conditional columns, as in the earlier chapters on masks and numpy.where:
import pandas as pd
status = pd.DataFrame({"status": ["ok", "ok", "down", "down", "ok"]})
status["changed"] = status["status"] != status["status"].shift()
print(status["changed"].tolist()) # [True, False, True, False, True]The first row is always True. NaN is not equal to any value, so the comparison with the shifted NaN gives True. That is usually what you want for "start of a new run". If it is not, set status.loc[0, "changed"] = False, or compare with shift(fill_value=...).
Combining shift and cumsum: run and session IDs
A cumulative sum of a boolean flag gives each run of rows its own number. Each True starts a new number, and False rows keep the current one. This replaces the loop that increments a counter when something changes.
The next example splits each user's events into sessions. A session ends when more than 30 minutes pass between events.
import pandas as pd
events = pd.DataFrame({
"user": ["u1", "u1", "u1", "u2", "u2"],
"ts": pd.to_datetime([
"2026-03-01 09:00", "2026-03-01 09:10", "2026-03-01 10:00",
"2026-03-01 09:05", "2026-03-01 09:20",
]),
})
events = events.sort_values(["user", "ts"]).reset_index(drop=True)
gap = events.groupby("user")["ts"].diff()
new_session = gap.isna() | (gap > pd.Timedelta("30min"))
events["session"] = new_session.astype(int).groupby(events["user"]).cumsum()
print(events["session"].tolist()) # [1, 1, 2, 1, 1]The steps are:
diffper user gives the time since that user's previous event. The first event of each user has no previous event, so its gap isNaT.gap.isna()marks each user's first event as a session start.gap > 30minmarks long pauses. The|combines the two masks.astype(int)turns the booleans into 0 and 1. A groupedcumsumthen numbers the sessions from 1 for each user.
The comparison gap > pd.Timedelta("30min") is False when gap is NaT. That is why the isna() term is needed.
Checking the result against the loop
The earlier chapter on measuring speed showed how to compare a rewrite with the original. The same discipline applies here, because off-by-one and group-boundary mistakes are common. Keep the loop as a reference and compare the two:
import pandas as pd
def running_total_loop(frame):
totals = {}
out = []
for row in frame.itertuples(index=False):
totals[row.store] = totals.get(row.store, 0) + row.amount
out.append(totals[row.store])
return pd.Series(out, index=frame.index)
def running_total_vec(frame):
return frame.groupby("store")["amount"].cumsum()
frame = pd.DataFrame({
"store": ["a", "a", "b", "a", "b"],
"amount": [10, 30, 5, 20, 15],
})
pd.testing.assert_series_equal(
running_total_loop(frame),
running_total_vec(frame),
check_names=False,
)
print("match")This frame has interleaved stores, so the test checks that state resets per group. The loop uses a dictionary for its state. groupby and cumsum give the same result in one pass over each column.
Summary of the translations
| Loop idiom | Vectorised form |
|---|---|
| `prev` variable updated each pass | `groupby(key)[col].shift(1)` |
| `row - prev` | `groupby(key)[col].diff()` |
| `row / prev - 1` | `groupby(key)[col].pct_change()` |
| `total += row` | `groupby(key)[col].cumsum()` |
| `best = max(best, row)` | `groupby(key)[col].cummax()` |
| Counter reset per key | `groupby(key).cumcount()` |
| Counter incremented on a condition | `flag.astype(int).cumsum()` |
When this approach stops working
These tools handle state that is a plain sum, maximum, or the previous value. They cannot express state that depends on a rule applied to its own earlier result. One example is a running balance that is clamped at zero after each step. Another is a counter that resets when it passes a threshold that depends on the running value. For each row, the next value depends on a decision made about the previous result. A single cumsum cannot capture that. The last chapter of this tutorial covers what to do then: itertuples, a compiled approach, or a rewrite of the rule.
Exercise
A DataFrame df has columns user, ts (datetime) and score, sorted by user and then ts. Write one line that adds a column best_so_far holding each user's highest score up to and including the current row. Then say what changes if you forget the groupby.
Show answer
df["best_so_far"] = df.groupby("user")["score"].cummax(). Without the groupby, cummax runs down the whole column, so one user's earlier high score carries over into the next user's rows.
Exercise
s = pd.Series([4, 7, 7, 9]). What is s.diff().dtype, and how do you get s.shift(1) to keep an integer dtype?
Show answer
s.diff().dtype is float64, because the first value is NaN. To keep integers, use s.shift(1, fill_value=0), which gives int64, or convert first with s.astype("Int64").shift(1), which keeps the nullable Int64 dtype and stores the missing value as <NA>.