Editor

Calculate Sales KPIs

Intermediate · Write the code · from Build a Sales Performance Dashboard with KPI Analysis

From the lesson: Step 2: Calculate Key Performance Indicators (KPIs)

KPIs are the numbers that tell you how the business is doing at a glance. For a sales team, the most important ones are total revenue, number of transactions, average order value, and total units sold. Let's calculate them all.

Read this part of the lesson

Write a function calculate_kpis(df) that takes a sales DataFrame (with a revenue and quantity column) and returns a dictionary with these keys:

  • total_revenue: sum of all revenue
  • transaction_count: number of rows
  • avg_order_value: mean revenue per transaction
  • total_units: sum of all quantities
  • avg_unit_price: total revenue divided by total units
  • Print each KPI formatted with 2 decimal places.

    import pandas as pd
    def calculate_kpis(df):
    # Your code here
    pass
    data = {
    'product': ['Laptop', 'Phone', 'Tablet', 'Laptop', 'Phone'],
    'quantity': [2, 5, 3, 1, 4],
    'unit_price': [999.99, 699.99, 449.99, 999.99, 699.99],
    }
    df = pd.DataFrame(data)
    df['revenue'] = df['quantity'] * df['unit_price']
    kpis = calculate_kpis(df)
    for key, value in kpis.items():
    print(f'{key}: {value:.2f}')

    More Sales Report exercises

    All Python exercises · 50 practice problems · Practical Projects quiz