Data Science · Level 2 Aggregation

pandas groupby

Total the revenue of each city with groupby(): split the rows into groups, sum each one and return the result as a plain dict.

  • df.groupby("col")["value"].sum()
  • The group keys become the index
  • .to_dict() for a plain dict

groupby splits rows by a column's values, then sum() or mean() runs on each group. Trap: select the value column first, or pandas tries to sum every other column too, text included.

orders = pd.DataFrame({"city": ["Paris", "Lyon", "Paris"], "total": [70, 40, 40]})
orders.groupby("city")["total"].sum().to_dict()
# {'Lyon': 40, 'Paris': 110}

Write revenue_by_city(df) that returns a dict mapping each city to the total of its amount column, for example {'Lyon': 40, 'Paris': 110}.

solution.py
Test Suites Pending
Output