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

25. How to Rank and Running Totals in pandas (rank, cumsum, window)

Data Science

25.1 Why Rank and Running Totals

Why. Shraddha Bagale (Pune ops) sorts amount_inr descending and pastes the sheet on WhatsApp. Amir asks: “Is BLK-10 still #1 after ties?” Ruhi asks: “What was cumulative delivered GMV by 6 pm IST?” Sort alone does not answer rank ties or running totals.

What.

  • Rank — place of a row among peers (1 = best if you rank high amounts first).
  • Running total (cumsum) — add values in order so each row shows “so far”.
  • Window — a moving or growing slice (last 3 days, or everything from day 1 until now).

How.

Pick the question first

  1. Write the manager question in one line.
  2. If it needs “#1 / #2 / tied” → rank.
  3. If it needs “GMV so far today” → sort by time, then cumsum.
  4. If it needs “last 3 days average” → rolling.
  5. Always check sort order before cumsum or rolling.

Worked example A — Sort vs rank.

import pandas as pd

df = pd.DataFrame({
    "order_id": ["BLK-1", "BLK-2", "BLK-3", "AMN-4"],
    "city": ["Pune", "Pune", "Nashik", "Pune"],
    "amount_inr": [210, 210, 95, 180],
    "customer": ["Ruhi Bagale", "Amir", "Zoya", "Ravina"],
})
print(df.sort_values("amount_inr", ascending=False))

Sorting shows order. Ranking labels ties clearly (next section).

Worked example B — Running total need (fictional evening).

Raja in Nagpur sends hourly delivered GMV. The city manager wants one column: cumulative GMV from midnight IST — that is cumsum, not a new groupby.

Worked example C — Decision card.

Question Tool
Top basket in Pune today rank (within city)
GMV so far this week cumsum after date sort
3-day moving average orders rolling(3).mean()

Ravindra Bagale's Tip

Write the business question first, and only then choose rank or cumsum. Always sort the data before cumsum, because a running total in the wrong order gives a wrong number. When you show ranks, write the tie rule (average, dense or min) in the caption so that people are not confused.