0 / 8 activities
APPLIED DATA ANALYTICS

Group by data analysis in Python: 10 Powerful Steps to Success

Master Group by data analysis in Python by investigating retail transactions, summarizing regional sales and product profitability, and turning your pandas results into a practical business recommendation.

Data AnalyticsPython · pandasGroup by
Start the project →
Group by data analysis in Python diagram showing transactions grouped into regional totals
01

The real-world scenario

Read the business brief before touching the code.

BUSINESS BRIEF

Imagine joining Meridian Retail, a fictional retailer selling electronics, home goods and office supplies across three sales regions. The finance team has delivered a transaction-level sales file, but managers still disagree about where the business performs best. The commercial director focuses on revenue, while the finance manager is more interested in gross profit. Both have reasonable concerns: a region can generate impressive sales while keeping only a small portion after paying for products. Without a consistent analysis, the company could direct its inventory and promotional budget toward the wrong markets.

Management wants a single report that compares North, South and West, along with the three product categories. You have 300 completed orders, each with an identifier, region, category, number of units, selling price and direct product cost in US dollars. Each record represents one order. The file does not include overhead, stock availability, returns or marketing expenditure. Your analysis must respect those boundaries and use the same financial definitions for every group.

Your final task is to identify the leading sales region, the most profitable product category and the strongest region-category combination. Management also wants to know how much each order contributes to its regional revenue. Deliver a reconciled summary and recommend which segment deserves closer investigation before the next inventory planning meeting.

02

Your role

YOUR ASSIGNMENT

Junior Data Analyst

You have joined Meridian Retail as a Junior Data Analyst. The finance manager has asked you to turn a detailed sales file into a report that regional managers can understand. Your responsibility is to translate their questions into measurable outcomes, examine the source data and decide how to summarize transactions without losing the financial meaning. You must also check that the results agree with the original dataset.

You will prepare the data, calculate order revenue and gross profit, build regional and category summaries, and examine combinations of both dimensions. You will then calculate profit margins and the contribution of each order. Finally, you will present the leading segments, explain the limitations of the available information and recommend an evidence-based next step for management.

03

Identify the problem

What is the core business problem, and which analytical method would you use to solve it?

Identify the business outcome, suitable technique and why you would choose it.

04

Investigate

Ask the right questions before developing your solution.

Q01What exactly does management want to measure?

Management needs to compare sales value and gross earnings at several levels. Revenue is the quantity sold multiplied by selling price. Direct cost is quantity multiplied by unit cost, and gross profit is the difference between revenue and direct cost. Gross margin is gross profit divided by revenue, expressed as a percentage. These measures answer different questions. Revenue shows the size of a market, while gross profit shows the money left after product cost. Orders count transactions, not individual units. Your report must keep these definitions consistent so that regional and category comparisons are meaningful.

Q02Which data fields and quality checks matter?

Start by examining the six original columns: order ID, region, category, units, unit price and unit cost. Each row represents one order, so the identifier should be unique in this file. Check that values are present and that quantities, prices and costs are positive. A missing region could cause pandas to omit a transaction during grouping by default. A missing price could distort the revenue total. A duplicate order could inflate both sales and profit. These checks are important because a neatly formatted report is not useful if the underlying transaction records are unreliable.

Q03Why use groupby instead of a predictive model?

The groupby method in pandas divides a table into groups that share the same key, applies a calculation to each group, and combines the results. This is often called split, apply and combine. For example, all North orders form one group and all South orders form another. Applying sum gives the total sales for each region. You can also use multiple keys, such as region and category, to create a more detailed summary. No predictive model is needed because management is asking about observed sales, not unknown future outcomes. This is a descriptive analysis task.

Q04How can you verify that the summaries are correct?

A correct report must reconcile to the original data. Add all regional revenue totals and compare the result with the sum of revenue in the original order table. The values should match because each order belongs to one region. Repeat the same reasoning for categories and combinations. For the order-level contribution measure, percentages within each region should add up to 100 percent. Allow a very small tolerance for floating-point rounding. Also inspect the number of groups and order counts. These checks test the logic of the analysis rather than using model accuracy or other irrelevant predictive metrics.

Q05How should management use the results?

The report helps management see where sales volume and gross profit tell different stories. A region with the largest revenue may have a product mix that generates a lower margin. Compare absolute gross profit with margin and the number of orders before choosing a segment to investigate. For example, a high-margin category with low sales might deserve a closer look, but limited demand could make expansion risky. Use the strongest region-category combinations as candidates for inventory and promotion review. The results describe the observed period only, so additional information about stock, demand and operating expenses is needed before committing funds.

05

Project resources

retail_sales.csv

CSV · 300 orders · 6 fields · USD

Download dataset ↓
order_idregioncategoryunitsunit_priceunit_cost
O001SouthElectronics3175148
O002NorthOffice63516
O003WestElectronics4175148
O004NorthElectronics5185148
O005NorthElectronics6185148

Data dictionary: order_id identifies each order; region and category are grouping keys; units is quantity; unit_price and unit_cost are USD per item.

06

Topic Lesson: Group by data analysis in Python

Explore the topic through interactive visual learning.

TOPIC LESSON
01 / 10
FOUNDATIONS

What is Group by data analysis in Python?

Grouping turns a detailed table into a useful summary. Pandas collects rows that share a common value, such as region, and calculates a result for each group. The input is a transaction table and the output is often a smaller table of totals, averages or counts. Instead of reading hundreds of orders, a manager can compare a few rows of regional performance. The method works with categorical labels, dates and other suitable grouping keys.

# Sum order revenue separately for each region.
df.groupby("region")["revenue"].sum()
Group by data analysis in Python workflowOrdersNorth · $20South · $40North · $30South · $10groupbyNorth$50South$50Split • Apply • Combine
Key takeaway: Group rows by a shared key, then calculate a result for each group.
1 / 10 slides explored
07

Build the solution

Complete the missing Python operations and run your analysis.

Retail performance analysis

Fill the missing identifiers in the code. Each hint explains the intended operation. Python runs in your browser after the runtime loads.

retail_analysis.py0 / 25 filled
# Import pandas for working with the retail sales table.
import as pd
# Read the retail sales CSV into a DataFrame.
df = pd.("retail_sales.csv")
# Display the number of rows and columns in the source table.
print(df.)
# Verify that each order ID appears only once.
assert df["order_id"].
# Check that every cell contains a value.
assert not df.().any().any()
# Require positive quantities, selling prices, and unit costs.
assert df[["units", "unit_price", "unit_cost"]].(0).all().all()
# Multiply units by the selling price to calculate revenue for each order.
df["revenue"] = df[""] * df["unit_price"]
# Multiply units by the unit cost to calculate each order’s total cost.
df["cost"] = df["units"] * df[""]
# Subtract total cost from revenue to calculate gross profit per order.
df["profit"] = df["revenue"] - df[""]
# Group orders by region to total revenue and profit and count orders.
regional = df.("region").agg(revenue=("revenue", "sum"), profit=("profit", "sum"), orders=("order_id", "size"))
# Divide each region’s total profit by its revenue to calculate gross margin as a percentage.
regional["margin_pct"] = regional["profit"].(regional["revenue"]) * 100
# Rank regions from highest to lowest revenue.
regional = regional.("revenue", ascending=False)
# For each category, total revenue, profit, and units, and count its orders.
category = df.groupby("category").(revenue=("revenue", "sum"), profit=("profit", "sum"), orders=("order_id", "size"), units=("units", "sum"))
# Convert each category’s profit-to-revenue ratio to a percentage.
category["margin_pct"] = category["profit"] / category[""] * 100
# Rank categories from highest to lowest gross profit.
category = category.sort_values("", ascending=False)
# Summarize revenue, profit, and order count for each region and category pair.
segments = df.groupby(["region", "category"], as_index=False).(revenue=("revenue", "sum"), profit=("profit", "sum"), orders=("order_id", "size"))
# Rank those region and category pairs from highest to lowest gross profit.
segments = segments.("profit", ascending=False)
# Attach the matching regional revenue total to each order.
df["region_total"] = df.groupby("region")["revenue"].("sum")
# Calculate each order’s percentage of its region’s revenue.
df["region_share_pct"] = df["revenue"].div(df[""]) * 100
# Add the order-level revenue shares within each region.
shares = df.groupby("region")["region_share_pct"].()
# Check that each region’s shares sum to 100 percent within a small rounding tolerance.
assert (shares.(100).abs() < 1e-8).all()
# Reconcile the sum of regional revenue with total revenue from the original orders.
assert regional["revenue"].sum() == df["revenue"].()
# Print the regional summary with values rounded to two decimal places.
print("REGIONS\n" + regional.(2).to_string())
# Print the category summary with values rounded to two decimal places.
print("CATEGORIES\n" + category.round(2).())
# Print the three highest-profit region and category pairs without row indices.
print("TOP SEGMENTS\n" + segments.(3).to_string(index=False))
08

End of the lesson

Reflect on your learning experience.

How was your learning experience?

Select a rating

Recommended resource

Explore additional learning resources to deepen your understanding.

Pandas grouping and aggregation illustration
UDEMY · COURSE RESOURCE

Data Analytics, Data Science, ML, DL & NLP - All in 1 Course

Explore a broader course covering Python data analysis, data preparation, visualization, statistics, SQL and machine learning.

View the complete course →