Zero Grad›كورس Data Analysis›Mini EDA›النوت بوك
← الدرسOpen in Kaggle

Mini EDA: where does the shop lose money?¶

This chapter puts the charts of this part to work on one business question about the NileCart sales table:

Some order lines lose money. Which ones, and why?

The charts are not explained again; the point is the order of the questions and why each chart was picked. The analysis goes from simple to rich:

  1. Univariate: one column at a time. What does it look like?
  2. Bivariate: two columns. What moves with what?
  3. Multivariate: three or more. Is it really one story?
  4. Conclusion: the answer, and what to do about it.

The chart follows from the columns in the question:

The question is about Chart
One number Histogram
One category Sorted bars
A number across categories Bars or box plot
Number vs number Scatter, or a correlation heatmap for many
A number over time Line
A number across two categories Heatmap
In [1]:
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns

sns.set_theme(style="whitegrid", palette=["#0F766E", "#E89B2D", "#D95D4A", "#152B3C", "#7C8B96"])
plt.rcParams.update({
    "figure.figsize": (8, 4.5),
    "axes.titlesize": 13,
    "axes.titleweight": "bold",
    "axes.spines.top": False,
    "axes.spines.right": False,
    "axes.formatter.limits": (-7, 9),
    "grid.alpha": 0.4,
    "legend.frameon": False,
})

sales = pd.read_csv("../data/nilecart/sales.csv", parse_dates=["order_date"])
sales["loss"] = sales["profit"] < 0
print(sales.shape, "| missing cells:", sales.isna().sum().sum())
print(sales["order_date"].min().date(), "to", sales["order_date"].max().date())
sales.head(3)
(1466, 19) | missing cells: 0
2024-01-01 to 2025-12-31
Out[1]:
order_id order_date customer_id name governorate region segment product_id product_name category quantity unit_price discount gross revenue unit_cost profit status loss
0 10002 2024-01-01 176 Fatma Hassan Cairo Greater Cairo Consumer 111 Notebook Stationery 5.0 63.0 0.00 315.0 315.0 20 215.0 cancelled False
1 10001 2024-01-01 132 Yasmin Mostafa Cairo Greater Cairo Corporate 101 Laptop Electronics 9.0 30400.0 0.05 273600.0 259920.0 27200 15120.0 completed False
2 10004 2024-01-02 131 Yasmin Fawzy Sharqia Delta Corporate 111 Notebook Stationery 10.0 57.0 0.00 570.0 570.0 20 370.0 completed False

The table is already clean: one row per order line, two full years.


1. Univariate: one column at a time¶

Question: What does profit per line look like, and how many lines are below zero? Chart: histogram, for one number. The line at 0 marks the border that matters.

In [2]:
fig, ax = plt.subplots()
sns.histplot(sales["profit"], bins=50, ax=ax)
ax.axvline(0, color="black", linewidth=1)
ax.set(title="Most lines earn a little, few earn a lot", xlabel="Profit per line (EGP)", ylabel="Order lines")
plt.show()
No description has been provided for this image
In [3]:
print("mean:", round(sales["profit"].mean()), "| median:", sales["profit"].median())
print("loss lines:", sales["loss"].sum(), "| total loss:", sales.loc[sales["loss"], "profit"].sum())
mean: 3680 | median: 1580.0
loss lines: 32 | total loss: -87860.0

📌 Insight: profit has a long right tail, so the mean (3,680) sits far above the median (1,580). Only 32 of 1,466 lines lose money, 87,860 EGP in total: small, but money the shop chose to lose.

Question: How often does the shop discount? Chart: count bars. discount is a number, but with only four values it behaves like a category.

In [4]:
fig, ax = plt.subplots(figsize=(6, 3.5))
sns.countplot(data=sales, x="discount", ax=ax)
ax.set(title="Half of our lines have no discount", xlabel="Discount", ylabel="Order lines")
plt.show()
No description has been provided for this image

📌 Insight: 51% of lines have no discount and 12% have the deep 20% one.

Question: What sells the most? Chart: sorted bars, for one category.

In [5]:
fig, ax = plt.subplots(figsize=(6, 3.5))
sns.countplot(data=sales, y="category", order=sales["category"].value_counts().index, ax=ax)
ax.set(title="Accessories are the most common line", xlabel="Order lines", ylabel="")
plt.show()
No description has been provided for this image

📌 Insight: Accessories lead with 602 lines and Electronics come second with 389. In money terms, though, one line of laptops is nothing like one line of notebooks, so the next step puts columns together.


2. Bivariate: two columns¶

Question: Which numeric columns move together? Chart: correlation heatmap. It screens every pair at once and shows where to look first.

In [6]:
corr = sales[["unit_price", "quantity", "discount", "revenue", "profit"]].corr()

fig, ax = plt.subplots(figsize=(6, 4.5))
sns.heatmap(corr, annot=True, fmt=".2f", cmap="RdBu_r", center=0, vmin=-1, vmax=1, ax=ax)
ax.set_title("Discount barely shows here")
plt.show()
No description has been provided for this image

📌 Insight: discount and profit: only -0.22, a weak link. That is not a reason to drop discounts from the analysis: one number for all products can hide what happens inside each category.

Question: Which categories actually bring the money? Chart: sorted bars of margin. Margin is profit as a share of revenue, so a 60 EGP notebook and a 32,000 EGP laptop stand on the same scale.

In [7]:
cat = sales.groupby("category")[["revenue", "profit"]].sum()
cat["revenue_share"] = cat["revenue"] / cat["revenue"].sum()
cat["profit_share"] = cat["profit"] / cat["profit"].sum()
cat["margin"] = cat["profit"] / cat["revenue"]
cat = cat.sort_values("margin", ascending=False)
cat.round(2)
Out[7]:
revenue profit revenue_share profit_share margin
category
Stationery 55351.20 35951.20 0.00 0.01 0.65
Accessories 1830641.70 918801.70 0.07 0.17 0.50
Furniture 3398060.05 1423370.05 0.12 0.26 0.42
Electronics 22556970.00 3016470.00 0.81 0.56 0.13
In [8]:
fig, ax = plt.subplots(figsize=(6, 3.5))
sns.barplot(x=cat["margin"], y=cat.index, ax=ax)
ax.set(title="Electronics have the thinnest margin", xlabel="Margin (profit / revenue)", ylabel="")
plt.show()
No description has been provided for this image

📌 Insight: Electronics bring 81% of revenue but only 56% of profit. Their margin is 13%, while every other category is at 42% or more. A thin margin leaves little room for a discount.

Question: What does a discount do to profit? Does it at least sell more units? Chart: bars of the mean, a number across four groups. Two panels side by side, same x-axis.

In [9]:
fig, axs = plt.subplots(1, 2, figsize=(10, 3.5), layout="constrained")

sns.barplot(data=sales, x="discount", y="profit", errorbar=None, ax=axs[0])
axs[0].set(title="Profit falls with the discount", xlabel="Discount", ylabel="Mean profit (EGP)")

sns.barplot(data=sales, x="discount", y="quantity", errorbar=None, ax=axs[1])
axs[1].set(title="Quantity doesn't move", xlabel="Discount", ylabel="Mean quantity")
plt.show()
No description has been provided for this image
In [10]:
sales.groupby("discount")[["profit", "quantity"]].mean().round(2)
Out[10]:
profit quantity
discount
0.00 4582.51 4.08
0.05 3787.78 4.12
0.10 2799.37 4.09
0.20 708.37 4.05

📌 Insight: mean profit drops from 4,583 EGP at no discount to 708 EGP at 20%, while quantity stays near 4 units per line. The discount does not make people buy more.

Question: Is there a time when margin gets worse? Chart: line, for a number over time, after adding up each month.

In [11]:
monthly = sales.groupby(sales["order_date"].dt.to_period("M"))[["revenue", "profit"]].sum()
monthly.index = monthly.index.to_timestamp()
monthly["margin"] = monthly["profit"] / monthly["revenue"]
monthly["margin"].sort_values().head(3).round(3)
Out[11]:
order_date
2025-11-01    0.124
2024-03-01    0.145
2024-11-01    0.146
Name: margin, dtype: float64
In [12]:
worst = monthly["margin"].idxmin()

fig, ax = plt.subplots(figsize=(9, 3.5))
ax.plot(monthly.index, monthly["margin"], marker="o")
ax.annotate("White Friday", xy=(worst, monthly["margin"].min()), xytext=(pd.Timestamp("2025-05-01"), 0.13),
            arrowprops={"arrowstyle": "->", "color": "black"})
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %y"))
ax.set(title="Margin hits its lowest point in November 2025", ylabel="Margin")
plt.show()
No description has been provided for this image

📌 Insight: the worst month of the two years is November 2025 (12%), and November 2024 is near the bottom too (15%). The overall margin is 19%.

That leaves three suspects: Electronics, the 20% discount and November. Three separate stories, or one? Answering that needs more than two columns.


3. Multivariate: three columns or more¶

Question: How does margin change with category and discount together? Chart: heatmap, a number across two categories. Margin keeps the categories comparable, and center=0 turns any loss red.

In [13]:
t = sales.groupby(["category", "discount"])[["profit", "revenue"]].sum()
pt = (t["profit"] / t["revenue"]).unstack()

fig, ax = plt.subplots(figsize=(7, 3.5))
sns.heatmap(pt, annot=True, fmt=".0%", cmap="RdYlGn", center=0, cbar=False, ax=ax)
ax.set(title="Only one cell loses money", xlabel="Discount", ylabel="")
plt.show()
No description has been provided for this image

📌 Insight: here is the hidden pattern. Every category stays profitable at every discount except Electronics at 20%, the only negative cell (-3%). The weak -0.22 was an average over categories that behave very differently.

Question: Is it every line in that cell, or a few bad ones? Chart: scatter of revenue vs profit, one dot per line. hue adds the discount, and one panel per category keeps the scales honest.

In [14]:
g = sns.relplot(data=sales, x="revenue", y="profit", hue="discount", col="category", col_wrap=2, palette="viridis",
                legend="full", alpha=0.7, height=3, aspect=1.4, facet_kws={"sharex": False, "sharey": False})
for ax in g.axes.flat:
    ax.axhline(0, color="black", linewidth=1)
g.set_titles("{col_name}")
plt.show()
No description has been provided for this image
In [15]:
sales[sales["loss"]].groupby(["category", "discount"]).size()
Out[15]:
category     discount
Electronics  0.2         32
dtype: int64

📌 Insight: only the Electronics panel goes below zero, and all 32 loss lines are Electronics at 20%, without a single exception.

Question: Is it one bad product? Chart: grouped bars: product on the x-axis, discount as hue, mean profit as height.

In [16]:
elec = sales[sales["category"] == "Electronics"]

fig, ax = plt.subplots(figsize=(9, 3.5))
sns.barplot(data=elec, x="product_name", y="profit", hue="discount", palette="viridis", errorbar=None, ax=ax)
ax.axhline(0, color="black", linewidth=1)
ax.set(title="All four Electronics products go negative at 20%", xlabel="", ylabel="Mean profit (EGP)")
plt.show()
No description has been provided for this image
In [17]:
costs = elec.groupby("product_name")[["unit_cost", "unit_price"]].median()
costs["cost_share"] = costs["unit_cost"] / costs["unit_price"]
costs.round(2)
Out[17]:
unit_cost unit_price cost_share
product_name
Laptop 27200.0 32000.0 0.85
Monitor 5700.0 7000.0 0.81
Phone 14600.0 18000.0 0.81
Tablet 9000.0 11000.0 0.82

📌 Insight: all four products are below zero, from Laptops (-5,504 EGP per line) to Monitors (-105 EGP). It is a pricing problem, not a product problem: their cost is 81% to 85% of the typical price, so 20% off sells most lines below cost.

Question: When do these losses happen? Chart: bars per month. These are counts, each month on its own, so bars read better than a line.

In [18]:
loss_m = sales.groupby(sales["order_date"].dt.to_period("M"))["loss"].sum()
loss_m.index = loss_m.index.to_timestamp()
nov = sales.loc[sales["loss"], "order_date"].dt.month.eq(11)
print("loss lines in November:", nov.sum(), "of", len(nov))

fig, ax = plt.subplots(figsize=(9, 3.5))
ax.bar(loss_m.index, loss_m.values, width=20)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %y"))
ax.set(title="Losses jump in November", ylabel="Loss lines")
plt.show()
loss lines in November: 14 of 32
No description has been provided for this image

📌 Insight: 14 of the 32 loss lines fall in the two Novembers. The three suspects are one story: White Friday pushes the 20% discount onto Electronics.


4. Conclusion¶

A decision maker needs one page, not every chart, so the summary keeps only the three that carry the answer.

In [19]:
fig = plt.figure(figsize=(12, 7.5), layout="constrained")
axd = fig.subplot_mosaic("AB;CC")

sns.heatmap(pt, annot=True, fmt=".0%", cmap="RdYlGn", center=0, cbar=False, ax=axd["A"])
axd["A"].set(title="Only one cell loses money", xlabel="Discount", ylabel="")
axd["A"].tick_params(axis="y", rotation=0)

sns.scatterplot(data=elec, x="revenue", y="profit", hue="discount", palette="viridis", legend="full", ax=axd["B"])
axd["B"].axhline(0, color="black", linewidth=1)
axd["B"].set(title="Electronics: every loss has a 20% discount", xlabel="Revenue (EGP)", ylabel="Profit (EGP)")

axd["C"].bar(loss_m.index, loss_m.values, width=20)
axd["C"].xaxis.set_major_formatter(mdates.DateFormatter("%b %y"))
axd["C"].set(title="Loss lines per month: White Friday is the peak", ylabel="Loss lines")

fig.suptitle("Losses come from 20% discounts on Electronics", fontsize=15, fontweight="bold")
Path("output").mkdir(exist_ok=True)
fig.savefig("output/where_we_lose_money.png", dpi=150, bbox_inches="tight")
plt.show()
No description has been provided for this image

Two checks before recommending anything: what is the fix worth, and does the answer change without the cancelled and returned lines?

In [20]:
deep = elec[elec["discount"] == 0.20]
extra = (deep["gross"] * 0.10).sum()
print("Electronics lines at 20%:", len(deep), "| profit now:", deep["profit"].sum())
print("profit at 10%:", deep["profit"].sum() + extra, "| gain:", extra)
print("gain as share of total profit:", round(extra / sales["profit"].sum(), 3))
Electronics lines at 20%: 43 | profit now: -75360.0
profit at 10%: 194870.0 | gain: 270230.0
gain as share of total profit: 0.05
In [21]:
kept = sales[sales["status"].isin(["completed", "shipped"])]
print("lines kept:", len(kept), "| loss lines:", kept["loss"].sum())
kept[kept["loss"]].groupby(["category", "discount"]).size()
lines kept: 1269 | loss lines: 19
Out[21]:
category     discount
Electronics  0.2         19
dtype: int64

The answer

  • Which lines lose money? Electronics at a 20% discount: all 32 loss lines, across all four products, and nothing else.
  • Why? Electronics have a thin margin, and 20% off takes most of those lines below cost. The discount does not raise the quantity per line either.
  • When? Any month, but White Friday is the peak: 14 of the 32 are in the two Novembers.

Recommendation: cap Electronics at 10% and keep the White Friday deals on everything else. Those 43 lines earned -75,360 EGP. At 10% they would earn about 194,870 EGP, a gain of 270,230 EGP, or 5% of total profit.

How sure is this? The pattern is solid: it holds with only completed and shipped orders (19 loss lines, all Electronics at 20%). But the gain assumes those lines would still sell at 10%, and this data cannot show the customers who came only for the 20%. The cap should be tested on the next White Friday before it becomes the rule.

Note the path: the univariate step showed that losses exist, the bivariate step produced three suspects, and only the multivariate step showed they are one story.


Next: Streamlit: turn charts like these into an interactive web app.