Sub topic 9
Previous-row and running-total logic
This chapter assumes you can build a DataFrame, use groupby, and write column arithmetic. It covers logic that looks like it needs a loop because each row depends on the row before it. Three methods handle most of these cases: shift, diff and the cumulative family.
Why these loops look unavoidable
A typical loop carries state from one row to the next. It might keep a previous value, or add to a running total.
import pandas as pd
sales = pd.DataFrame({
"store": ["a", "a", "b", "b"],
"amount": [10, 30, 5, 15],
})
running = 0
changes = []
totals = []
previous = None
for amount in sales["amount"]:
changes.append(None if previous is None else amount - previous)
running += amount
totals.append(running)
previous = amountNote that this loop ignores the stores, so it mixes store a and store b. The vectorised versions below fix that by working inside each group.
Shift: reading the previous row
shift(n) moves values down by n rows. The first n positions become NaN, because nothing comes before them. A negative n looks ahead instead.
sales["previous"] = sales.groupby("store")["amount"].shift(1)
sales["next"] = sales.groupby("store")["amount"].shift(-1)
print(sales)Calling shift on a groupby object stops values from crossing group boundaries. The first row of store b gets NaN, not the last amount from store a.
Diff: change from the previous row
diff is shorthand for column - column.shift(1).
sales["change"] = sales.groupby("store")["amount"].diff()
sales["change_manual"] = sales["amount"] - sales["previous"]Both columns hold the same values. Use diff for the common case and shift when you need the previous value itself, for example to compute a percentage change or to compare two columns.
Cumulative methods: running totals
cumsum, cumprod, cummax and cummin carry state down a column. Each also works per group.
sales["running_total"] = sales.groupby("store")["amount"].cumsum()
sales["best_so_far"] = sales.groupby("store")["amount"].cummax()
print(sales[["store", "amount", "change", "running_total", "best_so_far"]])The output is:
store amount change running_total best_so_far
0 a 10 NaN 10 10
1 a 30 20.0 40 30
2 b 5 NaN 5 5
3 b 15 10.0 20 15The change column is a float because it contains NaN. Missing values are skipped by cumsum and stay NaN in their own positions.
Rolling windows
Some logic looks back more than one row, such as a 3-row average. rolling covers this without a loop.
sales["avg_2"] = (
sales.groupby("store")["amount"]
.rolling(2, min_periods=1)
.mean()
.reset_index(level=0, drop=True)
)A grouped rolling result carries the group key in its index. The reset_index call removes that level so the result aligns with the original rows. This is the index alignment rule from the earlier chapter.
Common errors
- Forgetting
groupby, so one group's values leak into the next. - Sorting after computing.
shiftandcumsumfollow row order, so sort first, for example withsales.sort_values(["store", "date"]). - Expecting integers from
shiftordiff. TheNaNvalues turn the column into floats. - Assigning a grouped
rollingresult without dropping the extra index level.
When the next value depends on a rule that changes with each result, such as a balance that resets under a condition, these methods may not fit. The final chapter covers those cases.
Exercise
A DataFrame df has columns user, day and score, sorted by user then day. Write one line that adds a column gain holding each user's score minus their previous score, and say what value the first row of each user receives.
Show answer
df["gain"] = df.groupby("user")["score"].diff(). The first row of each user receives NaN, because there is no earlier row in that group.