In pandas, how do you add a running sales total, the previous sale and a sale number within each store using groupby?
answer
- same length as the input
- row order inside each group
- NaN at each group's first row
- numbering starts at zero
basics
~20 sCall cumsum, shift(1) and cumcount on df.groupby('store'). Each returns one value per input row, aligned to the original index and restarting at every store, in the frame's current row order, so sort by date first.
solid answer
~40 s`df.groupby('store')['amount'].cumsum()` returns a Series as long as `df` and indexed like it, so it assigns straight back as a column. It restarts at each store and walks the rows in the order they sit in the frame (groupby keeps the original order inside each group), so sort by date first; the stores need not be contiguous. `.shift(1)` gives each row the previous sale of its own store and `NaN` on each store's first row, which turns an `int64` column into `float64` unless you pass `fill_value`. `cumcount()` numbers the rows 0, 1, 2 inside each store, and `ngroup()` numbers the stores themselves from 0 in sorted-key order.
code
python · 16 linesimport pandas as pd
sales = pd.DataFrame({
"store": ["S1", "S2", "S1", "S3", "S2", "S1"],
"day": pd.to_datetime(["2026-03-01", "2026-03-01", "2026-03-02",
"2026-03-02", "2026-03-03", "2026-03-03"]),
"amount": [120, 50, 80, 30, 150, 200],
})
sales = sales.sort_values("day")
g = sales.groupby("store")["amount"]
sales["running"] = g.cumsum()
sales["prev"] = g.shift(1)
sales["sale_no"] = sales.groupby("store").cumcount() + 1
sales["store_no"] = sales.groupby("store").ngroup()
print(sales)
print(sales.dtypes)go deeper
Recall that cumsum, shift and cumcount on a groupby return one value per row, restart per group and assign straight back as columns. Sort by date first.
Explain why the result aligns by the original index, why shift opens a missing value on each group's first row, and why that turns an int64 column into float64.
Show you check row order and ties before trusting a running total, and that you know ngroup numbering depends on sort and on which keys are present.
Weigh whether running figures belong in the frame at all or in a reporting layer, and agree a team rule for ordering and tie-breaking so totals are reproducible.
## What a per-group running method returns A **groupby transformation** is a grouped operation whose result has the **same index as the object you grouped**. pandas ships several of them as methods on the GroupBy object: `cumsum`, `cumprod`, `cummax`, `cummin`, `cumcount`, `shift`, `diff`, `pct_change`, `rank`, `ffill` and `bfill`. Unlike `sum()` or `mean()`, which collapse each store to one row indexed by the store key, these return **one value per input row**, labelled with the original row labels. That is why the usual pattern is plain column assignment: ```python import pandas as pd sales = pd.DataFrame({ "store": ["S1", "S2", "S1", "S3", "S2", "S1"], "day": pd.to_datetime(["2026-03-01", "2026-03-01", "2026-03-02", "2026-03-02", "2026-03-03", "2026-03-03"]), "amount": [120, 50, 80, 30, 150, 200], }) sales = sales.sort_values("day") g = sales.groupby("store")["amount"] sales["running"] = g.cumsum() # 120, 50, 200, 30, 200, 400 sales["prev"] = g.shift(1) # NaN, NaN, 120.0, NaN, 50.0, 80.0 ``` The grouping column is not part of the result, and the `as_index` and `sort` arguments of `groupby` have no effect on a transformation, because the result is indexed like the input rather than by the keys. ## Row order decides the answer A running total only means something in a defined order. pandas does **not** sort rows by any value column before a cumulative method; it preserves the order in which rows appear **within each group**. So: - Sort by the time column (`sort_values('day')`) **before** grouping. Sorting by `['store', 'day']` also works, but sorting by store is not required: the stores can be interleaved and each one still accumulates on its own. - If two sales share a timestamp, the tie is broken by whatever order the sort left them in; pass `kind='stable'` to `sort_values` when that order must follow the input. - After a sort the index is no longer monotonic. Assignment still lines up by label, so the new column lands on the right rows. ## shift, cumcount and ngroup `shift(periods=1)` moves each value down by one row **inside its group**. The first row of every store has no predecessor, so it gets a missing value; a store's previous value never leaks into the next store, which is the bug a hand-written `sales['amount'].shift(1)` on the whole frame produces. `fill_value=0` fills those gaps instead. Subtracting `g.shift(1)` from the column, or calling `g.diff()`, gives the change since the store's previous sale. `cumcount()` returns each row's position within its group, **counting from 0**. Add 1 for a human sale number. `cumcount(ascending=False)` counts down to 0, so `== 0` marks each store's last row in the current order. `ngroup()` is its complement: it numbers the **groups**, not the rows, from 0 to the number of groups minus 1. The numbers follow the order in which the groups would be iterated, which with the default `sort=True` is sorted key order, not the order in which stores first appear. ## Dtypes you get back | call on an `int64` column | result | dtype | |---|---|---| | `g.cumsum()` | running total per store | `int64` | | `g.shift(1)` | previous value, missing on each first row | `float64` | | `g.shift(1, fill_value=0)` | previous value, 0 on each first row | `int64` | | `sales.groupby('store').cumcount()` | 0, 1, 2 within each store | `int64` | | `sales.groupby('store').ngroup()` | group number per row | `int64` (`float64` if a key is missing and `dropna=True`) | The `float64` from `shift` is the classic surprise: a missing value cannot live in a NumPy integer column, so pandas upcasts. Either fill it, or convert the column to the nullable `Int64` dtype afterwards if missing must stay distinguishable from zero. ## Mistakes to avoid 1. Expecting `cumsum` on a groupby to return one row per store; that is `sum`. 2. Forgetting to sort by time, then reading a running total that follows file order. 3. Shifting the ungrouped column and carrying one store's last sale into the next store's first row. 4. Treating `cumcount` as 1-based in a filter such as `cumcount() <= 3`, which keeps four rows per store. 5. Using `ngroup` as a stable store ID across files: the numbering depends on which keys are present and on `sort`. Windowed versions of these calculations, such as a seven-day rolling sum per store, belong with pandas rolling windows rather than cumulative methods.
- What does ngroup return for rows whose store key is missing?With the default `dropna=True`, a missing key is not a group, so `ngroup()` gives those rows `NaN` and the whole result becomes `float64`. Pass `dropna=False` to `groupby` and the missing key becomes a group of its own with an integer number, and the result stays `int64`.
- How do you mark the last sale of each store without sorting again?`sales.groupby('store').cumcount(ascending=False) == 0` is `True` on the last row of each store in the current row order, because the descending count ends at 0. Combined with a date sort, that marks each store's most recent sale while keeping every row.
- Does a grouped cumsum skip missing amounts or stop at them?It skips them: the missing row stays missing in the result and the running total resumes from the last valid value on the next row of the same store. Fill the gaps first, for example with `fillna(0)`, if a missing sale should count as zero.
- A grouped cumsum returns one row per store, like sum does
- The frame must be sorted by store before a grouped cumsum works
- groupby sorts rows by the date column before running cumulative methods
- cumcount starts counting at 1 inside each group
- A grouped shift carries the previous store's last value into the next store
- shift keeps an integer column as int64 even when it opens gaps