Editor

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 lesson

Write a function categorize_expense(description) that maps expense descriptions to categories using keyword matching:

  • Food: grocery, coffee, restaurant, lunch
  • Utilities: electric, phone, internet
  • Transport: gas, uber
  • Entertainment: movie, concert, streaming
  • Health: gym, pharmacy
  • Other: anything that doesn't match
  • 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

    All Python exercises · 50 practice problems · Practical Projects quiz