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 lessonWrite 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 revenuetransaction_count: number of rowsavg_order_value: mean revenue per transactiontotal_units: sum of all quantitiesavg_unit_price: total revenue divided by total unitsPrint 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
- Create and Prepare the Sales DataFrameIntermediate
- Revenue by Product and RegionIntermediate
- Find Top PerformersIntermediate
- Month-over-Month GrowthIntermediate
- Create a Summary ReportIntermediate
- Generate a Formatted ReportIntermediate
All Python exercises · 50 practice problems · Practical Projects quiz