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.
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.
Expert Problem Formulation
The core problem is not to forecast future sales or classify customers. It is to summarize existing transactions at the right level of detail. Group by data analysis in Python is an appropriate descriptive analytics technique because the questions concern totals, counts and ratios within known business groups. We already have region and category labels, so we do not need a model to discover those groups.
First, calculate revenue and direct cost at the order level. Gross profit is the difference between them. Then group the data by region and calculate the total revenue, total gross profit and number of orders in each group. Repeat the process for product categories. For margins, divide each group's total profit by its total revenue, rather than averaging order-level margins.
A second grouping with both region and category exposes specific business segments. An aggregation creates a smaller summary table, while a transformation can attach a group total to each original order. This makes it possible to compute the percentage of regional revenue contributed by each transaction without losing its original details.
The inputs are the six columns in the order file. The expected outputs are ranked regional, category and segment tables plus transaction-level shares. Reconcile the totals with the original records and check that shares add up to 100 percent in each region. This descriptive solution answers the management question without making unsupported forecasts or causal claims.
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.
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()
Key takeaway: Group rows by a shared key, then calculate a result for each group.
METHOD SELECTION
When should you group data?
Use grouping when a question contains phrases such as by region, per customer or for each category. It is useful for comparing revenue, average order value and order frequency across business segments. Use a filter instead when you only want to keep specific rows, and use a predictive model when the goal is to estimate an unknown future outcome. Here the labels are already available, so grouping is the simplest relevant method.
Question → measure + grouping key
Key takeaway: Use grouping for comparisons across known categories.
CORE CONCEPT
Split, apply and combine
Imagine four orders with revenues of 20, 30, 40 and 10 dollars. North contains the first two orders and South contains the last two. The split stage separates the rows into these groups. The apply stage adds the revenue within each group. The combine stage builds a result with one total per region. Notice that both groups have the same total even though the individual order values differ.
Begin by loading and validating the order table. Calculate order revenue and direct cost before grouping, then subtract cost to obtain gross profit. Build summaries using the keys that match management questions. Calculate ratios from grouped totals, sort the reports and reconcile the values against the input. The final step is to explain what the ranked summaries mean for management. This workflow keeps calculations traceable from raw records to business decisions.
Key takeaway: Calculate transaction measures before summarizing them.
MATHEMATICS
Calculate totals and weighted margins
The revenue for an order equals units times unit price. Group revenue is the sum of those values. Gross profit is revenue minus direct product cost. A group margin divides total gross profit by total revenue. In this illustrative example, one order earns 10 dollars on 20 dollars of sales and another earns 8 dollars on 80 dollars of sales. The combined margin is 18 percent, not the simple average of 50 and 10 percent.
Key takeaway: Use a ratio of totals for the group margin.
IMPLEMENTATION
Build summaries with groupby and agg
First call groupby with the name of the grouping column. Then use agg to apply multiple calculations. Named aggregation lets you choose a result column name, the original input column, and the operation. In the snippet, revenue is summed and orders are counted with size. The result contains one row per region. Use a list of column names in groupby to summarize multiple business dimensions at once.
# Group orders by region and start defining the summary columns.
regional = df.groupby("region").agg(
# Add the order revenues within each region.
revenue=("revenue", "sum"),
# Count how many order rows belong to each region.
orders=("order_id", "size")
# Finish the aggregation and store the regional summary.
)
Key takeaway: Named aggregation creates readable report columns.
IMPLEMENTATION
Keep original rows with transform
Sometimes a small summary is not enough. Transform returns a result aligned with every original row. Here we group revenue by region, compute a sum and attach that total to every transaction in its own region. Divide each order revenue by the attached group total to obtain its regional contribution. This is different from agg, which usually reduces the number of rows. Transform preserves the original transaction-level view.
# Attach the matching regional revenue total to each order.
df["region_total"] = df.groupby("region")["revenue"].transform("sum")
# Express each order’s revenue as a percentage of its regional total.
df["share"] = df["revenue"] / df["region_total"] * 100
Key takeaway: Use transform when every original row needs a group statistic.
VALIDATION
Evaluate and reconcile the output
The verified regional report contains three rows, one for each region. The total revenue is 97,485 dollars, and the three regional totals add up to exactly that value. The 300 orders are also accounted for across the groups. Check the sum of each region’s contribution percentages and allow a tiny tolerance around 100 percent. Reconciliation does not prove that source records are true, but it helps detect grouping and calculation mistakes.
# Reconcile the sum of regional revenue with total revenue from the original orders.
assert regional["revenue"].sum() == df["revenue"].sum()
Key takeaway: Every grouped total should reconcile to the source.
INTERPRETATION
Revenue is not the same as profit
The reference output shows that North leads sales at 39,590 dollars, while South produces the largest gross profit at 11,227 dollars. Electronics earns the most category revenue, but Home generates the most category gross profit. Office has the highest margin percentage, although its total profit is smaller. These differences matter because a manager who looks only at revenue might overlook groups that use sales value more efficiently.
Compare revenue, absolute gross profit and gross margin together.
Key takeaway: A sales leader is not necessarily a profit leader.
BUSINESS ACTION
Turn the strongest segment into a decision
South and Home together generate 5,869 dollars in gross profit, the highest observed region-category combination. Recommend that managers investigate this segment before allocating more stock or advertising. Compare its demand, inventory turnover, return rates and additional operating expenses with alternative segments. The analysis identifies a promising area for review, but the transaction file does not establish how much extra profit a new investment would produce. Use the results to guide a measured business experiment.
South / Home → review demand → test allocation → measure results
Key takeaway: Use descriptive results to prioritize investigation, not to promise future returns.
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.
01import as pd
# Read the retail sales CSV into a DataFrame.
02df = pd.("retail_sales.csv")
# Display the number of rows and columns in the source table.
03print(df.)
# Verify that each order ID appears only once.
04assert df["order_id"].
# Check that every cell contains a value.
05assert not df.().any().any()
# Require positive quantities, selling prices, and unit costs.
# Import pandas for working with the retail sales table.
import pandas as pd
# Read the retail sales CSV into a DataFrame.
df = pd.read_csv("retail_sales.csv")
# Display the number of rows and columns in the source table.
print(df.shape)
# Verify that each order ID appears only once.
assert df["order_id"].is_unique
# Check that every cell contains a value.
assert not df.isna().any().any()
# Require positive quantities, selling prices, and unit costs.
assert df[["units", "unit_price", "unit_cost"]].gt(0).all().all()
# Multiply units by the selling price to calculate revenue for each order.
df["revenue"] = df["units"] * df["unit_price"]
# Multiply units by the unit cost to calculate each order’s total cost.
df["cost"] = df["units"] * df["unit_cost"]
# Subtract total cost from revenue to calculate gross profit per order.
df["profit"] = df["revenue"] - df["cost"]
# Group orders by region to total revenue and profit and count orders.
regional = df.groupby("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"].div(regional["revenue"]) * 100
# Rank regions from highest to lowest revenue.
regional = regional.sort_values("revenue", ascending=False)
# For each category, total revenue, profit, and units, and count its orders.
category = df.groupby("category").agg(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["revenue"] * 100
# Rank categories from highest to lowest gross profit.
category = category.sort_values("profit", ascending=False)
# Summarize revenue, profit, and order count for each region and category pair.
segments = df.groupby(["region", "category"], as_index=False).agg(revenue=("revenue", "sum"), profit=("profit", "sum"), orders=("order_id", "size"))
# Rank those region and category pairs from highest to lowest gross profit.
segments = segments.sort_values("profit", ascending=False)
# Attach the matching regional revenue total to each order.
df["region_total"] = df.groupby("region")["revenue"].transform("sum")
# Calculate each order’s percentage of its region’s revenue.
df["region_share_pct"] = df["revenue"].div(df["region_total"]) * 100
# Add the order-level revenue shares within each region.
shares = df.groupby("region")["region_share_pct"].sum()
# Check that each region’s shares sum to 100 percent within a small rounding tolerance.
assert (shares.sub(100).abs() < 1e-8).all()
# Reconcile the sum of regional revenue with total revenue from the original orders.
assert regional["revenue"].sum() == df["revenue"].sum()
# Print the regional summary with values rounded to two decimal places.
print("REGIONS\n" + regional.round(2).to_string())
# Print the category summary with values rounded to two decimal places.
print("CATEGORIES\n" + category.round(2).to_string())
# Print the three highest-profit region and category pairs without row indices.
print("TOP SEGMENTS\n" + segments.head(3).to_string(index=False))
Complete code walkthrough
LINE 01
Import pandas
# Import pandas for working with the retail sales table.
import pandas as pd
Pandas is a Python library for working with tables. The import statement loads the library, and the alias pd gives it a shorter name. You will use this alias whenever you call a function belonging to pandas.
This line does not open the sales file or produce a table yet. It prepares the tools used throughout the project. Without it, Python would not recognize pd when you try to load the CSV file.
LINE 02
Load transaction data
# Read the retail sales CSV into a DataFrame.
df = pd.read_csv("retail_sales.csv")
The CSV file contains a header row and one row for every order. This pandas function parses the comma-separated values, recognizes the column labels and infers suitable data types for the numeric columns.
The returned DataFrame is stored in df. A DataFrame is a table with named columns and a row index. The same downloaded file is already available in the browser exercise, so no manual upload is necessary.
LINE 03
Check the table dimensions
# Display the number of rows and columns in the source table.
print(df.shape)
The shape attribute returns a tuple containing the row count followed by the column count. Unlike a method, it does not need parentheses. It helps you confirm that the expected file has been loaded.
Our input has 300 orders and six original columns. If the dimensions were unexpectedly smaller, you would investigate missing records before reporting revenue. The print function displays the tuple in the console without changing the DataFrame.
LINE 04
Check order uniqueness
# Verify that each order ID appears only once.
assert df["order_id"].is_unique
An order identifier should appear only once in this particular dataset. Selecting order_id returns a Series, which is a single labeled column. Its uniqueness property gives a Boolean value: True when no identifiers repeat.
The assert statement stops execution if the condition is false. In a real sales system, several lines might legitimately share one order ID. Here the business definition is one row per order, so duplicates need investigation rather than automatic deletion.
LINE 05
Check missing values
# Check that every cell contains a value.
assert not df.isna().any().any()
The missing-value method returns a Boolean table of the same shape as the original. True marks a missing cell. The first any operation reduces each column to one Boolean; the second reduces those values to a single answer.
The not keyword reverses that answer. The assertion therefore passes only when no cell is missing. This prevents an unknown region or missing price from silently affecting the totals. In production, missing records would need an agreed treatment.
LINE 06
Validate positive quantities and prices
# Require positive quantities, selling prices, and unit costs.
assert df[["units", "unit_price", "unit_cost"]].gt(0).all().all()
The double brackets select three numeric columns as a DataFrame. The comparison method checks each value against zero, producing True for every strictly positive entry. The two all operations reduce the Boolean table to one result.
This project contains completed sales, not returns or free samples. Positive units, prices and costs are part of its data contract. The check prevents these unexpected values from distorting the financial summary. Other retail datasets may require different rules.
LINE 07
Calculate order revenue
# Multiply units by the selling price to calculate revenue for each order.
df["revenue"] = df["units"] * df["unit_price"]
Revenue measures the amount earned from selling the products before deducting their costs. Multiply units sold by the selling price per unit. Pandas performs this calculation for every row without needing a Python loop.
For example, three items at 75 dollars produce 225 dollars of revenue. Assigning the result to a new column preserves the original quantities and prices while creating a common financial measure for all later group summaries.
LINE 08
Calculate order cost
# Multiply units by the unit cost to calculate each order’s total cost.
df["cost"] = df["units"] * df["unit_cost"]
The unit cost tells us how much one item costs the retailer. Multiplying it by the number of units gives the direct product cost for an entire order. This is not the same as selling price.
For example, three items costing 44 dollars each have a total direct cost of 132 dollars. We save the result in a separate cost column because management needs to compare both revenue and profitability across groups.
LINE 09
Calculate gross profit
# Subtract total cost from revenue to calculate gross profit per order.
df["profit"] = df["revenue"] - df["cost"]
Gross profit is revenue minus direct product cost. The subtraction is performed row by row, returning a Series aligned with the original index. We assign it to a new profit column.
An order earning 225 dollars with a cost of 132 dollars creates 93 dollars of gross profit. This measure excludes salaries, rent, advertising and other overhead, so do not describe it as net profit.
LINE 10
Summarize sales by region
# Group orders by region to total revenue and profit and count orders.
regional = df.groupby("region").agg(revenue=("revenue", "sum"), profit=("profit", "sum"), orders=("order_id", "size"))
The grouping method separates rows according to their region labels. The agg method applies several named aggregations in one operation: sum adds revenue and profit, while size counts the number of rows.
Each named aggregation pairs an input column with an operation. The returned DataFrame has one row per region, using region as its index. This is a compact management summary rather than a new collection of individual orders.
LINE 11
Calculate regional profit margin
# Divide each region’s total profit by its revenue to calculate gross margin as a percentage.
regional["margin_pct"] = regional["profit"].div(regional["revenue"]) * 100
The division method divides each regional gross profit by the revenue for the matching region. Multiplying by 100 converts the ratio into a percentage. Pandas aligns the two Series by their index labels.
Use the ratio of totals, not the average of individual order percentages. A large order should carry more weight than a tiny order when measuring overall margin. Revenue is positive in this dataset, so division by zero is not an issue.
LINE 12
Rank regions by revenue
# Rank regions from highest to lowest revenue.
regional = regional.sort_values("revenue", ascending=False)
Sorting the regional summary by revenue places the largest total at the top. The ascending parameter is False, which reverses the default increasing order. This returns a newly ordered table without changing the revenue values.
The result is assigned back to regional. This step makes the leading market easier to identify, but revenue ranking alone does not establish whether that market is the most profitable or has the strongest margin.
LINE 13
Build a category summary
# For each category, total revenue, profit, and units, and count its orders.
category = df.groupby("category").agg(revenue=("revenue", "sum"), profit=("profit", "sum"), orders=("order_id", "size"), units=("units", "sum"))
This time the grouping key is category instead of region. Named aggregation lets us calculate four measures in the same table, including total units sold. Each row of the result represents a product category.
Revenue indicates sales value, profit indicates direct earnings, orders shows transaction frequency, and units measures volume. These are different concepts. A category can sell many low-priced items while earning less revenue than a smaller premium category.
LINE 14
Compare category margins
# Convert each category’s profit-to-revenue ratio to a percentage.
category["margin_pct"] = category["profit"] / category["revenue"] * 100
Gross margin expresses the proportion of sales that remains after direct product costs. Here the numerator and denominator are already aggregated by category, so the calculation produces one meaningful percentage per product group.
A category earning 40 dollars of profit on 100 dollars of sales has a 40 percent margin. Managers can compare categories of different sizes using this ratio, but should also consider absolute profit and available inventory.
LINE 15
Rank categories by gross profit
# Rank categories from highest to lowest gross profit.
category = category.sort_values("profit", ascending=False)
The category summary is sorted by its profit column in descending order. This answers a different question from sorting by revenue: which group contributes the largest amount of gross earnings?
A high revenue category may have expensive inventory and therefore a low margin. Sorting by profit reveals which category contributes the most money after direct cost. The table still contains its revenue, orders, units and margin for comparison.
LINE 16
Group by two keys
# Summarize revenue, profit, and order count for each region and category pair.
segments = df.groupby(["region", "category"], as_index=False).agg(revenue=("revenue", "sum"), profit=("profit", "sum"), orders=("order_id", "size"))
Passing a list of two column names creates a separate group for each observed region and category combination. With as_index set to False, both group keys remain normal columns rather than becoming a hierarchical index.
The summary reveals patterns that a region-only or category-only table can hide. For example, Home products could perform differently across regions. These combinations can help managers decide where to investigate inventory or marketing opportunities.
LINE 17
Rank individual business segments
# Rank those region and category pairs from highest to lowest gross profit.
segments = segments.sort_values("profit", ascending=False)
The segment table is reordered using gross profit as the sorting key. Descending order places the strongest observed combination at the top, making comparisons straightforward for a management report.
This operation does not create new groups or change the calculated financial values. It simply changes presentation order. A leading combination might reflect larger demand, higher margins or both, which the analyst should investigate before recommending investment.
LINE 18
Broadcast regional totals
# Attach the matching regional revenue total to each order.
df["region_total"] = df.groupby("region")["revenue"].transform("sum")
The transform method computes a total for each region and returns that total alongside every original row from the region. Unlike an ordinary aggregation, its output has the same length and index as the input Series.
That makes it suitable for assignment directly into df. Each transaction now knows the revenue of its entire region. In the next line, this denominator will help calculate the transaction’s contribution to regional revenue.
LINE 19
Compute order contribution
# Calculate each order’s percentage of its region’s revenue.
df["region_share_pct"] = df["revenue"].div(df["region_total"]) * 100
Each order revenue is divided by its corresponding regional total. Multiplying by 100 turns the fraction into a percentage. The resulting column shows the contribution made by each order to its own region, rather than to the company overall.
An order worth 50 dollars in a region earning 500 dollars accounts for 10 percent. Adding these shares within a region should produce 100 percent, apart from tiny floating-point rounding differences.
LINE 20
Validate contribution percentages
# Add the order-level revenue shares within each region.
shares = df.groupby("region")["region_share_pct"].sum()
Grouping the contribution column by region and adding the values checks whether each region’s orders account for its total revenue. This returns one percentage per region rather than one value per transaction.
The expected value is 100 percent for every region. Small differences can arise from the way computers store decimal fractions. A large difference would suggest the denominator or grouping key is incorrect and should be investigated.
LINE 21
Test percentage reconciliation
# Check that each region’s shares sum to 100 percent within a small rounding tolerance.
assert (shares.sub(100).abs() < 1e-8).all()
The subtraction method compares every regional share total with 100. The absolute value removes the sign, and the comparison checks whether each difference is smaller than a tiny tolerance, one hundred-millionth.
The all method returns True only if every regional check passes. This is safer than testing exact floating-point equality. A reconciliation check helps catch logical mistakes even when the code itself runs without errors.
LINE 22
Reconcile total revenue
# Reconcile the sum of regional revenue with total revenue from the original orders.
assert regional["revenue"].sum() == df["revenue"].sum()
The left side adds revenue from the regional summary. The right side adds revenue directly from every order. Since every order belongs to exactly one region, both totals must match.
Revenue in this dataset uses whole dollar values, so exact equality is appropriate here. With fractional currency values you would normally use integer cents or a numerical tolerance. Passing this check confirms the regional report has preserved overall sales.
LINE 23
Display regional results
# Print the regional summary with values rounded to two decimal places.
print("REGIONS\n" + regional.round(2).to_string())
Rounding to two decimal places makes the percentage figures easier to read. The to_string method converts the DataFrame into a formatted text representation, and print sends it to the console with a heading.
This rounding is for presentation only. The underlying regional table is not overwritten, so full precision remains available for later calculations. The result lets management compare revenue, profit, order counts and margin across regions.
LINE 24
Display category results
# Print the category summary with values rounded to two decimal places.
print("CATEGORIES\n" + category.round(2).to_string())
The category table is rounded for display and then converted into text. This is useful in a terminal or browser console because it preserves the column headings and row labels in a compact report.
The report presents total revenue, gross profit, order counts, units and margins together. Management can distinguish a category with high sales from one with high gross earnings. The actual stored summary remains unchanged.
LINE 25
Report the three leading segments
# Print the three highest-profit region and category pairs without row indices.
print("TOP SEGMENTS\n" + segments.head(3).to_string(index=False))
The head method selects the first three rows of the segment table. Since we sorted that table by gross profit, these rows represent the three highest-profit region and category combinations in the dataset.
The index parameter is False when formatting the table, so the temporary row index is not displayed. The report gives management a practical shortlist for investigation, not a guarantee that future investment will deliver the same results.
Verified reference output
(300, 6)
REGIONS
revenue profit orders margin_pct
region
North 39590 10422 100 26.32
South 36515 11227 125 30.75
West 21380 6012 75 28.12
CATEGORIES
revenue profit orders units margin_pct
category
Home 30105 12329 106 404 40.95
Electronics 56215 10039 91 312 17.86
Office 11165 5293 103 367 47.41
TOP SEGMENTS
region category revenue profit orders
South Home 14405 5869 50
North Electronics 26355 4747 39
North Home 9480 3936 31
$97,485Total revenue
$27,661Gross profit
300Orders reconciled
Understanding the results
North records $39,590 in revenue, ahead of South ($36,515) and West ($21,380). But South earns $11,227 in gross profit compared with North’s $10,422. South’s 30.75% gross margin is higher than North’s 26.32%, so revenue ranking alone would miss an important profitability difference.
Home contributes $12,329 in gross profit even though Electronics generates $56,215 in revenue. Office has the highest gross margin (47.41%), but a lower absolute profit of $5,293. The segment table identifies South–Home as the highest-profit observed combination, with $5,869.
The regional sales total reconciles to $97,485, and order contribution percentages add to 100% in each region. The analysis meets the reporting objective, but it excludes overhead, returns, availability and future demand. These gross-profit comparisons cannot establish net profitability or causality.
BUSINESS RECOMMENDATION
$5,869
South · Home
Highest observed segment gross profit
Prioritize South–Home for the next inventory review. It produces $5,869 in gross profit, the highest amount among the nine observed region-category combinations. Home also leads total category gross profit at $12,329. Keep Electronics under review because it brings in the most category revenue, but its 17.86% gross margin is lower than the other categories.
Before moving inventory or increasing promotional spending, investigate stock turnover, lost sales, return rates and additional operating expenses. Run a small allocation test in South–Home and monitor incremental gross profit against a suitable comparison. Do not automatically reduce North’s inventory simply because its gross margin is lower. These findings summarize the available orders, rather than predicting future demand or proving that an investment will increase net profit.
08
End of the lesson
Reflect on your learning experience.
How was your learning experience?
Select a rating
Explore more lessons
Continue building practical skills with other interactive labs.
APPLIED DATA ANALYTICS
Data cleaning in python — 10 Essential Steps to Better Data
Practice Data cleaning in python on warehouse receipts. Inspect data types, fix inconsistent values, remove duplicates, and verify dock totals in a hands-on lab.
Data Joining in python — 3 Essential Checks for Better Parcel Pricing
Data Joining in python with pandas. Stack parcel manifests, merge zone tariffs, verify every shipment and reconcile delivery charges in an interactive coding lab.
Missing value in Python — 10 Essential Steps to Better Data
Learn to detect a Missing value in Python and use SimpleImputer to repair a delivery dataset. Explore 10 visual slides and run a hands-on Python exercise.
Pivot data analysis in Python — 10 Practical Steps to Better Decisions
Learn Pivot data analysis in Python with 10 visual lessons. Build pandas pivot tables from dispatch records, check late rates, and recommend a depot review.