Sub topic 3
Previous-Row and Running-Total Logic
This chapter assumes basic Python, pandas DataFrames, Series, dictionaries, and NumPy arrays. The goal is to replace row loops with operations that work on whole columns or groups.
Previous Rows and Running Totals
Use shift to access a previous row. Use diff to subtract the previous value. Use cumsum to calculate a running total. With groupby, each store or customer gets its own sequence.
import pandas as pd
sales = pd.DataFrame({
"store": ["a", "a", "b", "b"],
"amount": [10, 30, 5, 15],
})
sales["change"] = sales.groupby("store")["amount"].diff()
sales["running_total"] = sales.groupby("store")["amount"].cumsum()
print(sales)The first row in each group has no previous value, so change is NaN.
Replacing Per-Row Lookups
For a simple dictionary lookup, use map. For a lookup table with several columns, use merge.
rates = {"a": 0.10, "b": 0.20}
sales["rate"] = sales["store"].map(rates)
sales["tax"] = sales["amount"] * sales["rate"]
rate_table = pd.DataFrame({
"store": ["a", "b"],
"manager": ["Lee", "Sam"],
})
sales = sales.merge(rate_table, on="store", how="left")merge joins rows using matching key columns. Check that the key is unique when you expect one lookup row per key. Duplicate keys can unexpectedly multiply rows.
What Iteration Costs
apply(axis=1) is often clearer than iterrows, but it still calls Python once per row. iterrows also constructs a Series for each row and may change scalar types. itertuples is usually the fastest row iterator, but it remains a Python loop.
| Method | Typical use |
|---|---|
| Column expressions | Preferred for vectorisable work |
| `apply(axis=1)` | Convenient custom row logic |
| `itertuples()` | Faster fallback for unavoidable row logic |
Dtypes and Memory
Pandas can perform operations faster with suitable numeric and datetime dtypes. Convert text dates with pd.to_datetime, and avoid storing numbers as strings. Smaller numeric dtypes can reduce memory, but check that they can hold every value without overflow.
> callout note > Measure both speed and memory after rewriting. A faster expression is not useful if it changes results or creates an unexpectedly large intermediate column.
When a Loop Is Acceptable
A loop is reasonable for small data, stateful logic that depends on external systems, or logic that cannot be expressed with pandas operations. First try shift, diff, cumsum, map, merge, or a groupby method. If custom computation is still necessary, consider itertuples, NumPy, or a compiled approach such as Numba.
Exercise
Which pandas method calculates a separate running total for each store?
Show answer
Use sales.groupby("store")["amount"].cumsum().