Editor

Revenue by Product and Region

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

From the lesson: Step 3: Break Down Performance by Product and Region

Overall numbers are useful, but managers always want to drill down. Which product brings in the most revenue? Which region is underperforming? The groupby() method is how you answer these questions.

Read this part of the lesson

Write a function breakdown_by(df, column) that:

1. Groups the DataFrame by the given column

2. Calculates total revenue, total units sold, and transaction count per group

3. Sorts by total revenue descending

4. Returns the result DataFrame

The returned DataFrame should have columns: total_revenue, total_units, transactions.

Call it for both 'product' and 'region' and print the results.

import pandas as pd
def breakdown_by(df, column):
# Your code here
pass
data = {
'product': ['Laptop', 'Phone', 'Tablet', 'Laptop', 'Phone', 'Tablet'],
'region': ['North', 'South', 'North', 'East', 'South', 'East'],
'quantity': [2, 5, 3, 1, 4, 2],
'unit_price': [999.99, 699.99, 449.99, 999.99, 699.99, 449.99]
}
df = pd.DataFrame(data)
df['revenue'] = df['quantity'] * df['unit_price']
print('=== By Product ===')
print(breakdown_by(df, 'product'))
print('\n=== By Region ===')
print(breakdown_by(df, 'region'))

More Sales Report exercises

All Python exercises · 50 practice problems · Practical Projects quiz