You have an orders DataFrame and the city lead wants total revenue per city, biggest first.
Write a function revenue_by_city(df) that returns a Series indexed by city holding the summed amount, sorted from highest to lowest revenue.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Pune", "Delhi", "Pune", "Mumbai", "Delhi", "Pune", "Mumbai"],
"amount": [1200, 800, 450, 2600, 1750, 300, 900],
"channel": ["UPI", "Card", "UPI", "Card", "UPI", "COD", "UPI"],
}
)- Step 1: `df.groupby("city")` splits the rows into one group per city.
- Step 2: Selecting `["amount"]` *before* aggregating keeps the result a Series instead of a DataFrame — cheaper and simpler to sort.
- Step 3: `.sum()` collapses each group to a single total.
- Step 4: `.sort_values(ascending=False)` puts the biggest market first. Note `sort_values` sorts by value, `sort_index` would sort alphabetically by city.
import pandas as pd
def revenue_by_city(df):
return df.groupby("city")["amount"].sum().sort_values(ascending=False)Learn the concept first
Stuck on Pandas — GroupBy? These free Python lessons teach it step by step.
More Pandas — GroupBy questions
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program