Mission M30 · Python · 15 min

Sales by category with groupby

Request from your manager

The category manager asks: "Which product category brings in the most net sales, and how much?"

Data

Download the practice file(s):

Steps

  1. Load sales_flat.csv into a DataFrame.
  2. Use df.groupby('category')['net_sales'].sum().
  3. Sort with .sort_values(ascending=False) and round to 2 decimals.
  4. Print the top category and its value with .idxmax() and .max().

Check your answer

What are the total net sales of the top category?

Show solution

Dairy is #1 with $50,534.61, just ahead of Beverages ($50,340.95) and Frozen ($49,099.20). Produce is last ($22,493.35). (net_sales in the flat file is rounded per line, so totals can differ by about $1 from the SQL/DAX calculation.)

import pandas as pd

df = pd.read_csv('sales_flat.csv')
by_cat = df.groupby('category')['net_sales'].sum().round(2).sort_values(ascending=False)
print(by_cat)
print(by_cat.idxmax(), by_cat.max())

Answer: 50534.61 $