Categorize Expenses
Intermediate · Write the code · from Build a Budget Tracker and Expense Analyzer
From the lesson: Step 2: Categorize Expenses
Raw expense descriptions are messy. "Grocery store" and "Gas station" need to be mapped to budget categories like "Food" and "Transport." We'll build a mapping function that assigns each expense to its category.
Read this part of the lessonWrite a function categorize_expense(description) that maps expense descriptions to categories using keyword matching:
Then apply it to the DataFrame to create a category column, and print how many expenses are in each category.
import pandas as pd
def categorize_expense(description):
# Your code here
pass
expenses = {
'description': ['Grocery store', 'Electric bill', 'Coffee shop',
'Gas station', 'Restaurant', 'Movie tickets',
'Phone bill', 'Gym membership', 'Uber ride',
'Streaming service'],
'amount': [85.50, 120.00, 6.75, 45.00, 62.30, 28.00, 65.00, 40.00, 22.00, 15.99]
}
df = pd.DataFrame(expenses)
df['category'] = df['description'].apply(categorize_expense)
print(df[['description', 'category']].to_string(index=False))
print(f'\nExpenses per category:')
print(df['category'].value_counts().to_string())
More Budget Tracker exercises
- Create the Expense DataFrameIntermediate
- Spending Totals by CategoryIntermediate
- Budget ComparisonIntermediate
- Identify OverspendingIntermediate
- Complete Budget ReportIntermediate
All Python exercises · 50 practice problems · Practical Projects quiz