Ravindra BagaleCourses & study guides

7. GroupBy and Aggregations

7.1 Why GroupBy

In short: GroupBy splits rows into groups, applies a calculation, and combines the result — the split–apply–combine pattern.

GroupBy splits rows into groups, applies a calculation, and combines the result — the split–apply–combine pattern.

import pandas as pd

df = pd.DataFrame({
    "city": ["Pune", "Pune", "Nashik", "Nagpur", "Pune", "Solapur", "Kolhapur", "Sambhaji Nagar"],
    "festival": ["None", "Diwali", "Diwali", "None", "Ganeshotsav", "None", "None", "Diwali"],
    "amount": [64, 900, 450, 240, 320, 1299, 58, 195],
    "status": ["Delivered"] * 7 + ["Delivered"],
    "order_id": [f"BLK-{i}" for i in range(1, 9)],
})
df.groupby("city")["amount"].sum()
df.groupby("city")["amount"].agg(["sum", "mean", "count"])