End-to-End Customer Purchase Analysis Using Python
This project brings together the major concepts from Module 5 – Statistics
- Mean
- Median
- Mode
- Variance
- Standard Deviation
- Probability
- Normal Distribution
- Sampling
- Central Limit Theorem
- Hypothesis Testing
- p-value
- Confidence Intervals
- Correlation
- Covariance
- Chi-Square Test
- ANOVA
- Linear Regression
- Statistical Tests using Python
- Exploratory Data Analysis (EDA)
1. Project Objective
We will analyze an e-commerce customer dataset to answer questions such as
- What is the average customer spending?
- How widely does customer spending vary?
- Are customers from different membership groups spending differently?
- Is income related to purchase amount?
- Is membership type associated with purchasing behavior?
- Is there a statistically significant difference between customer groups?
- Can we predict purchase amount from customer characteristics?
The overall objective is
Use statistical analysis to understand customer behavior and build a simple model for predicting purchase amount.
2. Business Scenario
Imagine an e-commerce company called
ShopSmart
The company stores information about its customers.
Example data
| Customer ID | Age | Income | Membership | Purchases | Purchase Amount |
|---|
| C001 | 25 | 40000 | Basic | 3 | 250 |
| C002 | 32 | 55000 | Premium | 8 | 700 |
| C003 | 41 | 70000 | Premium | 10 | 950 |
| C004 | 22 | 30000 | Basic | 2 | 150 |
| C005 | 37 | 60000 | Gold | 12 | 1100 |
Our objective is to discover patterns in this data.
3. Dataset Structure
Let's assume our CSV contains
- customer_id
- age
- gender
- income
- membership
- purchase_count
- purchase_amount
- satisfaction
- city
- Variable types
| Variable | Type |
|---|
| customer_id | Identifier |
| age | Numerical |
| gender | Categorical |
| income | Numerical |
| membership | Categorical |
| purchase_count | Numerical |
| purchase_amount | Numerical |
| satisfaction | Numerical/ordinal |
| city | Categorical |
4. Project Structure
A professional project can be organized as
statistics_project/
│
├── data/
│ └── customers.csv
│
├── notebooks/
│ └── statistics_analysis.ipynb
│
├── src/
│ └── analysis.py
│
├── reports/
│ └── statistics_report.md
│
├── requirements.txt
▼
└── README.md
5. Required Python Libraries
Install
pip install numpy pandas scipy matplotlib seaborn statsmodels scikit-learn
Import
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
6. Load the Dataset
import pandas as pd
df = pd.read_csv("data/customers.csv")
print(df.head())Check the size
print(df.shape)
Example
(10000, 9)
This means
\[\boxed{10,000\text{ customers and }9\text{ columns}}\]
7. Initial EDA
Check the dataset structure
df.info()
Check statistics
df.describe()
Check categorical variables
df.describe(include="object")
Check missing values
df.isnull().sum()
Check duplicates
df.duplicated().sum()
8. Data Quality Analysis
We should investigate
Missing values
missing = df.isnull().sum()
print(missing)
Percentage
missing_percentage = (
df.isnull().mean() * 100
)print(missing_percentage)
Duplicates
print("Duplicates:", df.duplicated().sum())Data types
print(df.dtypes)
9. Descriptive Statistics
Let's analyze
df["purchase_amount"].describe()
Suppose we get
| Statistic | Value |
|---|
| Count | 10,000 |
| Mean | ₹650 |
| Std | ₹220 |
| Minimum | ₹50 |
| 25% | ₹500 |
| Median | ₹620 |
| 75% | ₹780 |
| Maximum | ₹2,500 |
We can conclude
The average purchase amount is approximately ₹650, while the median is ₹620.
Since
\[Mean>Median\]
the distribution may be somewhat right-skewed.
10. Mean, Median and Mode
Calculate
mean = df["purchase_amount"].mean()
median = df["purchase_amount"].median()
mode = df["purchase_amount"].mode()[0]
print("Mean:", mean)
print("Median:", median)
print("Mode:", mode)These provide different views of the center of the data.
Mean
\[\bar{x}\]
- Average purchase amount.
- Median
- Middle value.
- Mode
- Most frequently occurring value.
11. Variance and Standard Deviation
Calculate
variance = df["purchase_amount"].var()
std = df["purchase_amount"].std()
print("Variance:", variance)
print("Standard deviation:", std)If
\[SD=220\]
then customer purchase amounts typically vary around the mean by roughly 220 units, although standard deviation is not simply the average absolute distance.
12. Distribution of Purchase Amount
Create a histogram
plt.figure(figsize=(10, 6))
sns.histplot(
df["purchase_amount"],
kde=True
)
plt.title("Purchase Amount Distribution")
plt.xlabel("Purchase Amount")
plt.ylabel("Frequency")
plt.show()Look for
- Symmetry
- Skewness
- Multiple peaks
- Outliers
- Approximate normality
13. Box Plot
plt.figure(figsize=(10, 4))
sns.boxplot(
x=df["purchase_amount"]
)
plt.title("Purchase Amount Box Plot")
plt.show()This helps identify potential outliers.
14. Outlier Detection Using IQR
Calculate
Q1 = df["purchase_amount"].quantile(0.25)
Q3 = df["purchase_amount"].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
print("Lower:", lower_bound)
print("Upper:", upper_bound)Find potential outliers
outliers = df[
(df["purchase_amount"] < lower_bound) |
(df["purchase_amount"] > upper_bound)
]print(outliers)
15. Probability Analysis
Suppose we define a high-value customer as
\[PurchaseAmount>1000\]
We can estimate
\[P(Purchase>1000)\]
using
probability = (
(df["purchase_amount"] > 1000).mean()
)print(probability)
If the result is
0.12
then
\[\boxed{P(Purchase>1000)=0.12}\]
or
\[\boxed{12%}\]
16. Sampling
Suppose the full dataset contains
\[N=10,000\]
customers.
Take a random sample
sample = df.sample(
n=100,
random_state=42
)print(sample.head())
This allows us to study how sample statistics relate to population statistics.
17. Central Limit Theorem Demonstration
We can repeatedly sample the data and calculate the mean.
sample_means = []
for i in range(1000):
sample = df["purchase_amount"].sample(
n=100,
replace=True
)sample_means.append(
sample.mean()
)
Plot the sampling distribution
plt.figure(figsize=(10, 6))
sns.histplot(
sample_means,
kde=True
)
plt.title("Sampling Distribution of Mean")
plt.xlabel("Sample Mean")
plt.ylabel("Frequency")
plt.show()Even if the original distribution is not perfectly normal, the distribution of sample means tends toward normality as sample size increases under the conditions of the CLT.
This demonstrates the Central Limit Theorem.
18. Confidence Interval for Mean Purchase
Suppose
data = df["purchase_amount"].dropna()
n = len(data)
mean = data.mean()
std = data.std()
confidence = 0.95
alpha = 1 - confidence
t_critical = stats.t.ppf(
1 - alpha / 2,
df=n - 1
)margin = (
t_critical *
std /
np.sqrt(n)
)lower = mean - margin
upper = mean + margin
print("Mean:", mean)
print("95% CI:", lower, upper)We might obtain
\[\boxed{95%\ CI=[646,;654]}\]
Interpretation
Using this confidence-interval method, the population mean purchase amount is estimated to lie between approximately ₹646 and ₹654.
19. Hypothesis Test
Suppose the company believes
Average customer spending is ₹600.
We want to test
\[H_0:\mu=600\]
\[H_a:\mu\neq600\]
Run
result = stats.ttest_1samp(
df["purchase_amount"].dropna(),
popmean=600
)print("t-statistic:", result.statistic)
print("p-value:", result.pvalue)Suppose
\[p<0.05\]
Then
\[\boxed{\text{Reject }H_0}\]
Conclusion
There is statistically significant evidence that the average customer purchase amount differs from ₹600.
20. Correlation Analysis
Let's investigate
Is customer income related to purchase amount?
Calculate
correlation = df[
\["income", "purchase_amount"\]
].corr()
print(correlation)
Or
- r, p = stats.pearsonr(
- df["income"],
- df["purchase_amount"]
)
print("Correlation:", r)
print("p-value:", p)Suppose
\[r=0.72\]
Then income and purchase amount have a strong positive linear association.
21. Visualize Correlation
sns.scatterplot(
data=df,
x="income",
y="purchase_amount"
)
plt.title(
"Income vs Purchase Amount"
)plt.show()
A scatter plot helps us determine whether the relationship actually looks linear.
22. Covariance
Calculate
covariance = df[
"income"
].cov(
df["purchase_amount"]
)print("Covariance:", covariance)If covariance is positive
\[\boxed{Cov(X,Y)>0}\]
then the variables tend to move in the same direction.
Remember
Covariance is affected by the units of measurement, whereas correlation is standardized.
23. Chi-Square Test
Now consider two categorical variables
Membership
Purchase Status
Create a contingency table
table = pd.crosstab(
df["membership"],
df["purchase_status"]
)print(table)
Example
| Purchased | Not Purchased |
|---|
| Basic | 300 | 700 |
| Premium | 600 | 400 |
| Gold | 750 | 250 |
Now perform the chi-square test
chi2, p, dof, expected = (
stats.chi2_contingency(table)
)
print("Chi-square:", chi2)
print("p-value:", p)
print("Degrees of freedom:", dof)24. Chi-Square Interpretation
Hypotheses
\[H_0:\text{Membership and purchase status are independent}\]
\[H_a:\text{Membership and purchase status are associated}\]
Suppose
\[p<0.05\]
Then
\[\boxed{\text{Reject }H_0}\]
Conclusion
There is statistically significant evidence of an association between membership type and purchase status.
Again
\[\boxed{\text{Association}\neq\text{Causation}}\]
25. ANOVA
Now ask
Does average purchase amount differ among membership groups?
Groups
Run
basic = df.loc[
df["membership"] == "Basic",
"purchase_amount"
].dropna()premium = df.loc[
df["membership"] == "Premium",
"purchase_amount"
].dropna()gold = df.loc[
df["membership"] == "Gold",
"purchase_amount"
].dropna()Run ANOVA
result = stats.f_oneway(
basic,
premium,
gold
)print("F-statistic:", result.statistic)
print("p-value:", result.pvalue)26. ANOVA Interpretation
Hypotheses
[
H_0:
\mu_{Basic}
\mu_{Premium}
\mu_{Gold}
]
Alternative
\[H_a:\text{At least one mean differs}\]
If
\[p<0.05\]
we reject (H_0).
Conclusion
There is statistically significant evidence that average purchase amounts are not all equal across membership groups.
To determine which groups differ, use a post-hoc test such as Tukey HSD.
27. Tukey HSD
from statsmodels.stats.multicomp import pairwise_tukeyhsd
data = df[
\["membership", "purchase_amount"\]
].dropna()
tukey = pairwise_tukeyhsd(
endog=data["purchase_amount"],
groups=data["membership"],
alpha=0.05
)print(tukey)
This can tell us whether
- Basic vs Premium
- Basic vs Gold
- Premium vs Gold
- show statistically significant differences.
28. Linear Regression
Now let's build a model to predict
\[PurchaseAmount\]
using
- Income
- Age
- Purchase count
Our model is
\[\boxed{
PurchaseAmount=
\beta_0+
\beta_1Income+
\beta_2Age+
\beta_3PurchaseCount
}\]
29. Prepare the Data
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
features = [
"income",
"age",
"purchase_count"
]model_data = df[
features + ["purchase_amount"]
].dropna()X = model_data[features]
y = model_data["purchase_amount"]
30. Train/Test Split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.20,
random_state=42
)
This creates
80% → Training
20% → Testing
31. Train Regression Model
model = LinearRegression()
model.fit(
X_train,
y_train
)Get coefficients
print("Intercept:", model.intercept_)
print("Coefficients:", model.coef_)32. Make Predictions
predictions = model.predict(X_test)
print(predictions[:10])
33. Evaluate the Model
Calculate
from sklearn.metrics import (
mean_absolute_error,
mean_squared_error,
r2_score
)mae = mean_absolute_error(
y_test,
predictions
)mse = mean_squared_error(
y_test,
predictions
)rmse = np.sqrt(mse)
r2 = r2_score(
y_test,
predictions
)print("MAE:", mae)
print("MSE:", mse)
print("RMSE:", rmse)
print("R²:", r2)34. Understanding the Metrics
Suppose we obtain
MAE = 85
RMSE = 120
R² = 0.72
- MAE
- On average, predictions differ from actual values by about 85 units in absolute terms.
- RMSE
- Penalizes larger errors more heavily than MAE.
- R²
\[R^2=0.72\]
means the model explains approximately
\[\boxed{72%}\]
of the variation in the target within the evaluated data under the usual (R^2) interpretation.
35. Regression Residual Analysis
Calculate residuals
residuals = y_test - predictions
Plot
sns.scatterplot(
x=predictions,
y=residuals
)
plt.axhline(
0,
linestyle="--"
)plt.xlabel("Predicted")
plt.ylabel("Residual")
plt.title("Residual Plot")
plt.show()We want residuals to look reasonably pattern-free.
A systematic curve or changing spread can indicate problems with the model assumptions.
36. Statistical Summary of the Project
At the end of the project, you should be able to answer
- Descriptive Statistics
- Mean purchase amount?
- Median?
- Standard deviation?
- Variance?
- Probability
- Probability of high-value purchase?
- Distribution
- Is purchase amount approximately normal?
- Is it skewed?
- Sampling
- What happens to sample means?
- Confidence Interval
- What is the estimated population mean?
- What is its confidence interval?
- Hypothesis Testing
- Is the mean different from the company's benchmark?
- Correlation
- Is income associated with purchase amount?
- Covariance
- Do income and purchase amount move together?
- Chi-Square
- Is membership associated with purchase status?
- ANOVA
- Do membership groups have different average purchase amounts?
- Regression
- Can we predict purchase amount?
37. Project Dashboard
A useful final EDA dashboard could contain
┌─────────────────────────────────────────────────────┐
│ CUSTOMER STATISTICS DASHBOARD │
├────────────┬────────────┬────────────┬──────────────┤
│ Customers │ Avg Spend │ Median │ Std Dev │
│ 10,000 │ ₹650 │ ₹620 │ ₹220 │
├────────────┴────────────┴────────────┴──────────────┤
│ │
│ Purchase Amount Distribution │
│ Histogram │
│ │
├─────────────────────────┬───────────────────────────┤
│ Income vs Purchase │ Purchase by Membership │
│ Scatter Plot │ Box Plot │
│ │ │
├─────────────────────────┴───────────────────────────┤
│ Correlation Heatmap │
├─────────────────────────────────────────────────────┤
│ Key Statistical Findings │
│ • Mean purchase = ₹650 │
│ • Income correlation = 0.72 │
│ • ANOVA p-value < 0.05 │
│ • Membership associated with purchase status │
└─────────────────────────────────────────────────────┘
38. Final Project Report Structure
Your final report can contain
1. Executive Summary
Briefly explain
- Business problem
- Dataset
- Major findings
- Recommendations
2. Dataset Description
Explain
- Number of rows
- Number of columns
- Variables
- Data types
3. Data Quality
Document
- Missing values
- Duplicates
- Invalid values
- Outliers
4. Exploratory Data Analysis
Include
- Descriptive statistics
- Histograms
- Box plots
- Bar charts
- Scatter plots
- Correlation heatmap
5. Statistical Analysis
Include
- Confidence interval
- Hypothesis testing
- p-values
- Chi-square
- ANOVA
- Correlation
6. Regression
Explain
- Predictors
- Coefficients
- R²
- MAE
- RMSE
- Residual analysis
7. Findings
Summarize the important discoveries.
8. Business Recommendations
Explain what the company should do based on the evidence.
9. Limitations
Discuss
- Sample size
- Data quality
- Potential bias
- Assumptions
- Causality limitations
10. Conclusion
Provide the overall conclusion.
39. Example Final Findings
Suppose your analysis produces
Average Purchase Amount = ₹650
Median Purchase Amount = ₹620
Standard Deviation = ₹220
High-value customer rate = 12%
Income-Purchase correlation = 0.72
Correlation p-value < 0.05
ANOVA p-value < 0.05
Chi-square p-value < 0.05
Regression R² = 0.72
A possible conclusion
Customer spending shows substantial variation, with a moderate right-skew caused by higher-value purchases. Income has a strong positive association with purchase amount. Customer membership is statistically associated with purchasing behavior, and average purchase amounts differ significantly across membership groups. The regression model explains approximately 72% of the variation in purchase amount, suggesting that income, age, and purchasing behavior contain useful predictive information.
40. Important Statistical Cautions
A professional statistics project should not blindly treat every (p<0.05) as a major discovery.
Always consider
Statistical significance
\[p<0.05\]
- Effect size
- How large is the effect?
- Confidence interval
- How uncertain is the estimate?
- Sample size
- How much data supports the result?
- Practical significance
- Does the result matter to the business?
- Multiple testing
- If you run many tests, some may appear significant simply by chance.
- Causality
- Observational relationships do not automatically establish causal relationships.
41. Complete Project Workflow
The entire project can be summarized as
RAW DATA
▼
Load with Pandas
▼
Data Profiling
↓
┌──────────┴──────────┐
↓ ↓
Data Quality Structure
↓ ↓
Missing / Duplicates Data Types
Outliers / Errors Categories
└──────────┬──────────┘
↓
EDA
↓
┌───────────────┼────────────────┐
↓ ↓ ↓
Univariate Bivariate Multivariate
↓ ↓ ↓
Distribution Correlation Patterns
Outliers Relationships Interactions
└───────────────┼────────────────┘
↓
Statistical Analysis
↓
┌───────────────┼────────────────┐
↓ ↓ ↓
Confidence Hypothesis Statistical
Intervals Tests Tests
↓
┌───────────────┼────────────────┐
↓ ↓ ↓
Chi-Square ANOVA Correlation
↓ ↓ ↓
└───────────────┼────────────────┘
↓
Linear Regression
▼
Model Evaluation
▼
Business Insights
▼
FINAL REPORT
42. Module 5 — Final Revision
You have now completed the entire Statistics module
| # | Topic | Core Idea |
|---|
| 5.1 | Mean | Average |
| 5.2 | Median | Middle value |
| 5.3 | Mode | Most frequent value |
| 5.4 | Variance | Measure of spread |
| 5.5 | Standard Deviation | Typical spread around mean |
| 5.6 | Probability | Likelihood of events |
| 5.7 | Normal Distribution | Bell-shaped distribution |
| 5.8 | Sampling | Studying samples |
| 5.9 | Central Limit Theorem | Sampling means tend toward normality |
| 5.10 | Hypothesis Testing | Formal statistical decisions |
| 5.11 | p-value | Evidence against (H_0) |
| 5.12 | Confidence Intervals | Estimate + uncertainty |
| 5.13 | Correlation | Linear association |
| 5.14 | Covariance | Joint variation |
| 5.15 | Chi-Square | Categorical frequency analysis |
| 5.16 | ANOVA | Compare 3+ means |
| 5.17 | Linear Regression | Model/predict numerical outcomes |
| 5.18 | Statistical Tests using Python | Apply tests programmatically |
| 5.19 | EDA | Understand and investigate data |
| 5.20 | Statistics Project | Apply everything end-to-end |
Final Takeaway
The most important skill from this module is not memorizing formulas.
It is learning to go from
\[\boxed{\text{Business Question}}\]
to
\[\boxed{\text{Data}}\]
to
\[\boxed{\text{EDA}}\]
to
\[\boxed{\text{Statistical Test}}\]
to
\[\boxed{\text{Evidence}}\]
to
\[\boxed{\text{Business Decision}}\]
For a Data Scientist, the complete mindset is
Understand the data → visualize it → quantify it → test assumptions → perform the appropriate statistical analysis → measure uncertainty → communicate the result clearly.
That completes Module 5 – Statistics.