25. How to Rank and Running Totals in pandas (rank, cumsum, window)
25.3 cumsum: Running Totals
Why. A bar chart of daily GMV does not show “by Thursday we already crossed ₹5 lakh”. Running totals do.
What. cumsum() adds values in the current row order. Wrong order → wrong story. Usually: sort by date (and maybe city), then cumsum.
How.
Daily running GMV
- Build or load a day-level table (
order_date,gmv). df = df.sort_values("order_date").df["gmv_running"] = df["gmv"].cumsum().- Print the last row — that is week-to-date / month-to-date.
- Export for Chapter 22 style CSV if managers want Excel.
Worked example A — Festival week (fictional).
import pandas as pd
week = pd.DataFrame({
"order_date": pd.to_datetime(
["2026-10-20", "2026-10-21", "2026-10-22", "2026-10-23", "2026-10-24"]
),
"gmv": [82000, 91000, 88000, 125000, 140000],
"city_note": ["Mon", "Tue", "Wed", "Thu Diwali eve", "Fri"],
})
week = week.sort_values("order_date")
week["gmv_running"] = week["gmv"].cumsum()
print(week)
Worked example B — Share of running total.
week["pct_of_week_so_far"] = (week["gmv_running"] / week["gmv"].sum() * 100).round(1)
print(week[["order_date", "gmv", "gmv_running", "pct_of_week_so_far"]])
Worked example C — Cumcount for order sequence.
orders = pd.DataFrame({
"order_id": ["BLK-a", "BLK-b", "BLK-c"],
"city": ["Pune", "Pune", "Pune"],
})
orders["seq"] = range(1, len(orders) + 1) # simple
# or: orders["seq"] = orders.groupby("city").cumcount() + 1
print(orders)
Ravindra Bagale's Tip
cumsum works like the memory button on a calculator, because it keeps adding as it goes. Always sort by date before you use it, or Friday may get added before Thursday. A running total on unsorted data looks fine, but it tells a false story.
Ravindra Bagale's Tip – मराठी
cumsum हे calculator च्या memory button सारखं काम करतं, कारण ते पुढे जाताना बेरीज करत राहतं. ते वापरण्याआधी data नेहमी date नुसार sort करा, नाहीतर Thursday च्या आधी Friday ची बेरीज होऊ शकते. Sort न केलेल्या data वरचा running total ठीक दिसतो, पण चुकीची गोष्ट सांगतो.
Ravindra Bagale's Tip – हिंदी
cumsum calculator के memory button की तरह काम करता है, क्योंकि यह आगे बढ़ते हुए जोड़ता रहता है। इसे इस्तेमाल करने से पहले data को हमेशा date के हिसाब से sort करो, वरना Thursday से पहले Friday जुड़ सकता है। बिना sort वाले data पर running total ठीक दिखता है, लेकिन गलत कहानी बताता है।