Data Science · E-commerce
Data Science Applications in E-commerce: Real-World Examples
Quick summary — data science in e-commerce
E-commerce companies use data science for product recommendations, demand forecasting before sales and festivals, search ranking based on relevance and behaviour, experiments on pricing and page design, and predicting return risk to improve size guidance and reduce costs. Each example can become a portfolio project with public data.
In this guide you will learn:
- Recommendation systems — item similarity and co-purchase.
- Demand forecasting — with seasonality and features.
- Search, experiments and returns — with working code.
- E-commerce project templates — for your portfolio.
- Interview questions — for e-commerce data science roles.
SECTION 01Recommendations: helping shoppers find products
Recommendations appear on home pages, product pages, carts and emails. They help shoppers discover products they may like and can increase basket size. Approaches range from simple rules, such as showing items often bought together, to models based on user behaviour. Many teams start with simple, explainable approaches and improve them through testing. Common types include:
| Type | How it works | Where it appears | Data needed |
|---|---|---|---|
| Popular items | Most viewed or bought in a category | Home page, new users | Orders, views |
| Bought together | Items often in the same order | Product page, cart | Order line items |
| Similar items | Items with similar attributes or viewers | Product page | Attributes, view history |
| Personalised | Based on a user's own behaviour | Home page, emails | User history |
from collections import Counter
from itertools import combinations
orders = [
["phone", "case", "charger"],
["phone", "case"],
["laptop", "mouse"],
["phone", "charger"],
["laptop", "mouse", "bag"],
]
pairs = Counter()
for items in orders:
for a, b in combinations(sorted(set(items)), 2):
pairs[(a, b)] += 1
def bought_with(item, top=2):
scores = Counter({(b if a == item else a): n
for (a, b), n in pairs.items() if item in (a, b)})
return scores.most_common(top)
print(bought_with("phone"))
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
# rows = users, columns = items (1 = viewed)
items = ["kurta", "jeans", "sneakers", "saree", "t-shirt"]
views = np.array([
[1, 0, 0, 1, 0],
[0, 1, 1, 0, 1],
[1, 0, 0, 1, 0],
[0, 1, 1, 0, 0],
])
sim = cosine_similarity(views.T) # item-item similarity
idx = items.index("jeans")
ranked = sorted(zip(items, sim[idx]), key=lambda x: -x[1])
print([name for name, s in ranked if name != "jeans"][:2])
SECTION 02Demand forecasting: stocking the right products
E-commerce companies and their sellers need to know how much stock to keep in each warehouse. Too little stock means lost sales during peaks; too much means storage costs and discounting later. Data scientists build demand forecasts using past sales, seasonality, promotions and events such as festivals and sale days. These are the key elements:
| Element | What it captures | Example feature | Why it matters |
|---|---|---|---|
| Trend | Long-term growth or decline | Rolling average | Base level of demand |
| Seasonality | Repeating patterns | Day of week, month | Weekly and yearly cycles |
| Events | Festivals and sales | Is-sale-day flag | Sharp demand spikes |
| Price and promotions | Discounts and offers | Discount percent | Demand responds to price |
import numpy as np
import pandas as pd
from sklearn.ensemble import GradientBoostingRegressor
rng = np.random.default_rng(0)
dates = pd.date_range("2025-01-01", periods=400, freq="D")
df = pd.DataFrame({"date": dates})
df["dow"] = df["date"].dt.dayofweek
df["month"] = df["date"].dt.month
df["sale_day"] = (df["date"].dt.day == 10).astype(int)
df["units"] = (50 + 10 * (df["dow"] >= 5) + 80 * df["sale_day"]
+ rng.normal(0, 5, len(df))).round()
train, test = df.iloc[:360], df.iloc[360:]
X = ["dow", "month", "sale_day"]
m = GradientBoostingRegressor(random_state=0).fit(train[X], train["units"])
mae = (m.predict(test[X]) - test["units"]).abs().mean()
print("MAE on last 40 days:", round(mae, 1))
import pandas as pd
# Always compare with a simple baseline:
# predict this week's demand = same day last week
sales = pd.Series([52, 49, 51, 55, 60, 72, 75,
53, 50, 52, 56, 61, 70, 78])
baseline = sales.shift(7)
mae = (sales - baseline).abs().dropna().mean()
print("seasonal naive MAE:", round(mae, 2))
# A model is only useful if it beats this.
SECTION 03Search ranking, experiments and return prediction
When shoppers search for a product, the order of results strongly affects what they buy. E-commerce teams also run controlled experiments to test changes before launching them widely, and they analyse returns, which are costly in fashion and electronics. Data science supports all three areas, often working closely with product and operations teams:
| Application | Question | Method | Outcome |
|---|---|---|---|
| Search ranking | Which results should appear first? | Relevance plus click and purchase signals | More useful results |
| A/B testing | Did the new product page help? | Randomised test with control group | Evidence-based launches |
| Return prediction | Which orders are likely to be returned? | Classification on order and item features | Better size guidance |
| Review analysis | What do customers complain about? | Text grouping and keyword analysis | Product and listing fixes |
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
products = [
"cotton kurta for women blue",
"running shoes for men lightweight",
"blue denim jeans slim fit",
"women cotton saree printed",
]
vec = TfidfVectorizer()
P = vec.fit_transform(products)
query = "blue cotton kurta"
scores = cosine_similarity(vec.transform([query]), P)[0]
for score, name in sorted(zip(scores, products), reverse=True)[:3]:
print(round(score, 2), name)
import pandas as pd
from sklearn.linear_model import LogisticRegression
orders = pd.DataFrame({
"is_fashion": [1, 1, 0, 1, 0, 1, 0, 1],
"size_differs_from_usual": [1, 0, 0, 1, 0, 1, 0, 0],
"first_purchase": [1, 0, 1, 1, 0, 0, 0, 1],
"returned": [1, 0, 0, 1, 0, 1, 0, 0],
})
X, y = orders.drop(columns="returned"), orders["returned"]
m = LogisticRegression().fit(X, y)
new = pd.DataFrame([{"is_fashion": 1, "size_differs_from_usual": 1, "first_purchase": 1}])
print("return risk:", round(m.predict_proba(new)[0][1], 2))
# Use: show a size guide prompt, not a penalty.
SECTION 04E-commerce data science project templates
Use public e-commerce datasets to build these projects for your portfolio:
1. Bought-together recommender from public order data
Metric: hit rate on held-out orders vs popular-items baseline
2. Demand forecast for top 20 products
Metric: MAE vs seasonal naive baseline, time-based split
3. Review analysis for one category
Output: top complaint themes with examples
# Bought-Together Recommender
## Problem
Suggest relevant add-on items on the product page.
## Data
Public order dataset: orders, items, categories.
## Approach
Co-purchase counts, compared with popular items.
## Results
Hit rate: baseline vs model (held-out orders).
## Limitations and next steps
[ ] Business question written first
[ ] Simple baseline built
[ ] Time-based split for forecasting
[ ] Metric linked to business value
[ ] Charts that a manager can read
[ ] Limitations stated honestly
[ ] Code runs from a clean environment
SECTION 05Tips for e-commerce data science roles
These habits help you stand out for e-commerce data science roles:
- Start with baselines — popular items and last-week demand are strong benchmarks.
- Use time-based splits — never let future data leak into training.
- Think about the shopper — use models to help customers, not frustrate them.
- Learn experimentation — A/B testing is central to e-commerce decisions.
- Understand seasonality — festivals and sale days shape demand in India.
SECTION 06Interview Q&A — e-commerce DS
Q1How would you build a simple recommendation system?
Start with popular items and co-purchase counts, evaluate on held-out orders, then try similarity or personalised models and test the best in an A/B experiment.
Q2How do you evaluate a demand forecast?
Use a time-based split, compare errors such as MAE with a seasonal naive baseline, and check performance on peaks and promotions.
Q3Why can a random train/test split be wrong for forecasting?
It lets the model see future data while training, which leaks information and makes performance look better than in real use.
Q4How would you test a new product page design?
Randomly split users into control and test groups, define a primary metric such as conversion, run for enough time and check significance and side effects.
Q5How could return prediction be used responsibly?
To improve size guidance, product descriptions and quality checks, rather than to penalise individual customers.
SECTION 07Test yourself — e-commerce DS quiz
Five questions. No sign-up.
0 / 5Pick an answer to see why it is right or wrong.
SECTION 08Frequently asked questions
How is data science used in e-commerce?
For recommendations, demand forecasting, search ranking, pricing and page experiments, return prediction, fraud checks and review analysis. These help shoppers find products and help companies plan stock and operations.
What skills do e-commerce data scientists need?
Python, SQL, statistics, machine learning, forecasting, experimentation and the ability to connect models to business metrics.
Can I build e-commerce data science projects with public data?
Yes. Public e-commerce, retail and review datasets are available and suitable for recommendation, forecasting and text analysis projects.
Is recommendation system knowledge needed for e-commerce roles?
It helps, especially basic approaches and how to evaluate them. Many roles also focus on forecasting, experiments and analytics.
How is this different from data analytics in e-commerce?
Analytics focuses more on reporting and explaining what happened. Data science adds predictive models, experiments and systems that make or support decisions automatically.
SECTION 09Related reads
Classroom & online · Noida
Build real e-commerce data science projects
Our Data Science Training Course covers Python, statistics, machine learning, forecasting and experimentation with industry-style projects.
Talk to a counsellor for current fees- Recommendation projects
- Forecasting and experiments
- Portfolio support
- Weekday & weekend batches