# 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))
