Editor

Spending Totals by Category

Intermediate · Write the code · from Build a Budget Tracker and Expense Analyzer

From the lesson: Step 3: Calculate Totals by Category

Now that every expense has a category, we can calculate how much was spent in each category. This is the core of budget analysis: grouping expenses and summing them up.

Read this part of the lesson

Write a function spending_by_category(df) that:

1. Groups by the category column

2. Calculates total spending, number of transactions, and average transaction amount per category

3. Sorts by total spending (highest first)

4. Returns the result as a DataFrame with columns: total, count, average

Print the result.

import pandas as pd
def spending_by_category(df):
# Your code here
pass
data = {
'category': ['Food', 'Food', 'Food', 'Utilities', 'Utilities',
'Transport', 'Transport', 'Entertainment', 'Health'],
'amount': [85.50, 62.30, 6.75, 120.00, 65.00, 45.00, 22.00, 28.00, 40.00]
}
df = pd.DataFrame(data)
result = spending_by_category(df)
print(result)

More Budget Tracker exercises

All Python exercises · 50 practice problems · Practical Projects quiz