Ravindra BagaleCourses & study guides मराठी Track your progress

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

  1. Build or load a day-level table (order_date, gmv).
  2. df = df.sort_values("order_date").
  3. df["gmv_running"] = df["gmv"].cumsum().
  4. Print the last row — that is week-to-date / month-to-date.
  5. 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 = calculator chi memory. Pan pehle sort — nahi tar Thursday Friday chya aadhi yeto.