Python Notes
Learn exploratory data analysis (EDA) with Python, Pandas, and NumPy. Master descriptive statistics, correlation analysis, group comparisons, time series basics, and building insight-driven data reports.
Exploratory Data Analysis (EDA) is the process of investigating a dataset to discover patterns, spot anomalies, and test hypotheses using statistical summaries and visualizations. It's the foundation of every data science project.
Setup
pip install pandas numpy scipy matplotlib seabornimport pandas as pd
import numpy as np
from scipy import stats
import warnings
warnings.filterwarnings('ignore')Loading the Dataset
We'll use a realistic e-commerce sales dataset throughout this lesson:
Descriptive Statistics
Categorical Analysis
Sales Trend Analysis
Customer Analysis (RFM)
Correlation Analysis
Distribution Analysis
Group Comparison (A/B Analysis)
Return Analysis
Time Series Rolling Statistics
Generating a Summary Report
Summary
In this lesson, you learned:
- ✅ Setting up and loading a realistic dataset
- ✅ Descriptive statistics (mean, median, std, skewness, kurtosis)
- ✅ Categorical frequency analysis and crosstabs
- ✅ Time-based trend analysis (monthly, weekly, hourly)
- ✅ Customer segmentation with RFM analysis
- ✅ Correlation analysis and significance testing
- ✅ Distribution and percentile analysis
- ✅ Group comparisons with statistical tests
- ✅ Return analysis and rolling statistics
- ✅ Generating a comprehensive EDA report
📤 Expected Outputs
Loading the Dataset Output
Dataset shape: (1000, 13) order_id date customer_id product ... total_amount month day_of_week hour 0 1000 2025-01-01 00:00:00 202 Mouse ... 149.95 1 Wednesday 0 1 1001 2025-01-01 08:00:00 548 Monitor ... 399.00 1 Wednesday 8 2 1002 2025-01-01 16:00:00 387 Keyboard ... 239.97 1 Wednesday 16 3 1003 2025-01-02 00:00:00 330 Laptop ... 4995.00 1 Thursday 0 4 1004 2025-01-02 08:00:00 156 Webcam ... 89.99 1 Thursday 8
Descriptive Statistics Output
=== DATASET OVERVIEW ===
Records: 1000
Columns: 13
Date range: 2025-01-01 to 2025-12-14
Unique customers: 467
Total revenue: $586,432.78
=== NUMERIC STATISTICS ===
quantity unit_price total_amount
count 1000.0 1000.00 1000.00
mean 2.9 291.16 586.43
std 1.4 353.22 1012.88
min 1.0 29.99 29.99
25% 2.0 79.99 89.99
50% 3.0 149.99 239.97
75% 4.0 399.00 999.00
max 5.0 999.00 4995.00
=== REVENUE DISTRIBUTION ===
Mean order value: $586.43
Median order value: $239.97
Std deviation: $1012.88
Min order: $29.99
Max order: $4995.00
Q1 (25th pct): $89.99
Q3 (75th pct): $999.00
Skewness: 2.134
Kurtosis: 4.567Categorical Analysis Output
=== PRODUCT SALES ===
count percentage
Mouse 182 18.2
Keyboard 178 17.8
Monitor 170 17.0
Headphones 168 16.8
Laptop 154 15.4
Webcam 148 14.8
=== REVENUE BY CATEGORY ===
total_revenue avg_order order_count revenue_pct
Computers 298745.12 923.45 324 50.9
Peripherals 178543.89 351.27 508 30.5
Audio 109143.77 649.67 168 18.6Sales Trend Analysis Output
=== MONTHLY REVENUE ===
revenue orders avg_order
Jan 52345.67 93 562.86
Feb 48912.34 88 555.82
Mar 61234.56 102 600.34
Apr 55678.90 96 579.99
May 49876.12 91 548.09
=== SALES BY DAY OF WEEK ===
sum mean count
Monday 87654.12 578.50 152
Tuesday 83245.67 582.14 143
Wednesday 86321.45 590.56 146
Thursday 85432.78 575.90 148
Friday 88765.34 598.42 148
Saturday 79876.23 565.43 141
Sunday 75137.19 547.53 122Customer Analysis (RFM) Output
=== CUSTOMER SEGMENTS ===
count avg_recency avg_frequency avg_monetary
Champions 45 12.3 4.8 3245.67
Loyal Customers 89 34.5 3.5 1876.34
New Customers 67 8.2 1.3 456.78
At Risk 78 89.4 3.2 1567.89
Lost 56 125.6 1.1 234.56
Regular 132 56.7 2.1 987.45Correlation Analysis Output
=== CORRELATION MATRIX ===
quantity unit_price total_amount month hour
quantity 1.000 -0.012 0.456 0.003 0.001
unit_price -0.012 1.000 0.721 0.008 -0.005
total_amount 0.456 0.721 1.000 0.011 -0.003
month 0.003 0.008 0.011 1.000 0.002
hour 0.001 -0.005 -0.003 0.002 1.000
High Correlations:
var1 var2 correlation
unit_price total_amount 0.7210
quantity total_amount 0.4560
Pearson R between quantity and total_amount:
r = 0.4560, p-value = 0.000001
Significant at p < 0.05Distribution Analysis Output
Shapiro-Wilk normality test: stat=0.7234, p=0.000001 Distribution: Not Normal === REVENUE PERCENTILES === P10: $29.99 P25: $89.99 P50: $239.97 P75: $999.00 P90: $1,995.00 P95: $2,997.00 P99: $4,995.00 === ORDER SIZE DISTRIBUTION === <$50 112 $50-100 198 $100-200 156 $200-500 234 $500-1000 167 >$1000 133
Group Comparison Output
=== REGIONAL PERFORMANCE ===
total_revenue avg_order_value order_count return_rate customers revenue_per_customer
North 175929.83 586.43 300 0.05 156 1127.75
South 117286.56 586.43 200 0.04 108 1086.00
East 146608.20 586.43 250 0.05 127 1154.40
West 146608.19 586.43 250 0.06 123 1191.93
North vs South t-test: t=0.1234, p=0.9018
Difference is not significantRolling Statistics Output
=== DAILY REVENUE (Sample) ===
daily_revenue rolling_7_mean rolling_7_std
2025-12-05 1456.78 1623.45 345.67
2025-12-06 2345.12 1689.23 401.23
2025-12-07 987.34 1578.90 367.89
2025-12-08 1876.45 1645.12 389.45
2025-12-09 1234.56 1598.67 356.78
2025-12-10 1567.89 1612.34 378.90
=== WEEKLY REVENUE ===
week_revenue WoW_change MA_4week
2025-12-01 10234.56 -5.23 11234.56
2025-12-08 11456.78 11.94 11034.67
2025-12-14 8976.34 -21.64 10567.89EDA Report Output
======================================================================
EXPLORATORY DATA ANALYSIS REPORT
======================================================================
📊 DATASET OVERVIEW
Rows: 1,000
Columns: 13
Missing values: 0
Duplicate rows: 0
💰 TARGET: total_amount
Total: $586,432.78
Mean: $586.43
Median: $239.97
Std: $1,012.88
🏷️ CATEGORICAL SUMMARY
product (6 unique):
Mouse: 182 (18.2%)
Keyboard: 178 (17.8%)
Monitor: 170 (17.0%)
region (4 unique):
North: 300 (30.0%)
East: 250 (25.0%)
West: 250 (25.0%)
🔗 CORRELATIONS WITH total_amount
unit_price: 0.7210
quantity: 0.4560
hour: -0.0030
month: 0.0110✅ Key Takeaways
- 🎯 EDA हर data science project की foundation है — model बनाने से पहले data को अच्छे से समझना जरूरी है
- 📊 Descriptive statistics से शुरुआत करो — mean, median, std, skewness, kurtosis से data की basic nature समझ आती है
- 🔢
describe()powerful है but not enough — custom aggregations (groupby,agg) से deeper insights मिलते हैं - 📈 Time series analysis से trends पता चलते हैं — monthly, weekly, hourly patterns business decisions drive करते हैं
- 👥 RFM Analysis customer segmentation का gold standard है — Recency, Frequency, Monetary से actionable segments बनते हैं
- 🔗 Correlation ≠ Causation — statistical significance (p-value) check करो, और always domain context consider करो
- 📉 Distribution check करो normality test से — Shapiro-Wilk test बताता है data normal है या नहीं, जो further analysis methods decide करता है
- ⚖️ Group comparisons में t-test / ANOVA use करो — "significant difference" prove करने के लिए statistical tests जरूरी हैं
- 🔄 Rolling statistics smoothed trends दिखाते हैं — noise हटाकर actual patterns identify करने में help करते हैं
- 📋 Automated EDA reports बनाओ — functions लिखो जो reusable हों, ताकि हर dataset पर same analysis quickly run कर सको
❓ FAQ
Q1: EDA और Data Analysis में क्या difference है?
Answer: EDA (Exploratory Data Analysis) data analysis का एक specific phase है जो project की शुरुआत में होता है। इसमें हम data को explore करते हैं — patterns, anomalies, relationships discover करते हैं। Data Analysis broader term है जिसमें EDA, hypothesis testing, reporting, visualization सब आता है। सोचो EDA को "getting to know your data" phase। 🔍
Q2: Pandas describe() vs custom statistics — कब क्या use करें?
Answer: describe() quick overview के लिए perfect है — mean, std, min, max, quartiles एक line में मिल जाते हैं। But जब specific business questions answer करने हों (जैसे "region-wise average order value" या "top 10% customers का revenue share"), तब groupby() + agg() use करो। Real projects में दोनों साथ use होते हैं — describe() से start करो, custom stats से deep dive करो। 📊
Q3: Correlation matrix में कौनसे values significant हैं?
Answer: Generally: |r| > 0.7 = Strong correlation, 0.4 < |r| < 0.7 = Moderate, |r| < 0.4 = Weak। But सिर्फ value देखना enough नहीं है — scipy.stats.pearsonr() से p-value भी check करो। अगर p > 0.05 है, तो correlation statistically significant नहीं है, चाहे r value कुछ भी हो। Large datasets में small correlations भी significant आ जाती हैं, इसलिए effect size (r value) ज्यादा important है। 🔗
Q4: RFM Analysis real business में कैसे use होती है?
Answer: RFM बहुत practical है! Champions segment को premium offers दो (loyalty rewards), At Risk customers को win-back campaigns भेजो (discounts), New Customers को onboarding emails दो, Lost customers को re-engagement campaigns। E-commerce companies जैसे Amazon, Flipkart extensively RFM use करती हैं email marketing personalization के लिए। Score 1-5 scale पर रखो और segments बनाओ। 🎯
Q5: Shapiro-Wilk test fail हो तो क्या करें?
Answer: अगर data normal नहीं है (p < 0.05 in Shapiro-Wilk), तो: (1) Non-parametric tests use करो (Mann-Whitney instead of t-test, Kruskal-Wallis instead of ANOVA), (2) Log transformation try करो (np.log1p(data)), (3) Large samples (n>30) में Central Limit Theorem apply होता है, तो means approximately normal होते हैं। Real-world data rarely perfectly normal होता है — don't panic! 📉
Q6: groupby() में agg() vs apply() — कब क्या?
Answer: agg() use करो जब standard aggregations चाहिए (sum, mean, count, etc.) — ये faster है और multiple columns पर different functions apply कर सकता है। apply() use करो जब custom/complex logic चाहिए जो standard functions से possible नहीं (जैसे top-N items per group, या conditional calculations)। Performance: agg() >> apply() especially large datasets पर। 🚀
Q7: Time series analysis में resample() vs groupby() — difference क्या है?
Answer: resample() specifically time-based grouping के लिए designed है — DatetimeIndex require करता है और frequency strings ('D', 'W', 'M') accept करता है। groupby(df['date'].dt.month) भी काम करेगा but resample() के advantages: (1) handles missing periods, (2) supports forward/backward fill, (3) rolling windows compatible। Time series work में हमेशा resample() prefer करो। ⏰
Q8: EDA automated tools (pandas-profiling/ydata-profiling) vs manual EDA — कौनसा better?
Answer: Both have their place! ydata-profiling (earlier pandas-profiling) quick overview देता है — एक line में full HTML report। But manual EDA से specific business questions answer कर सकते हो, custom visualizations बना सकते हो, और domain-specific analysis कर सकते हो। Best practice: automated report से start करो (overview), फिर manual EDA करो (deep dive)। Interviews में manual EDA demonstrate करना ज्यादा impressive है। 🏆
🎯 Interview Questions
Q1: What is Exploratory Data Analysis and why is it important?
Answer: EDA is the process of analyzing datasets to summarize their main characteristics, often using statistical graphics and other data visualization methods. It's important because:
- Discovers patterns — trends, seasonality, clusters identify होते हैं
- Finds anomalies — outliers, missing data, data quality issues detect होते हैं
- Tests assumptions — normality, independence, homogeneity verify करते हैं
- Guides modeling — feature selection, transformation decisions inform करता है
- Communicates findings — stakeholders को data story tell करता है
Real example: E-commerce data पर EDA करके discover किया कि 80% revenue top 20% customers से आती है (Pareto principle), which led to a VIP loyalty program. 📊
Q2: Explain the difference between mean, median, and mode. When would you use each?
Answer:
- Mean (average) — sum/count, sensitive to outliers. Use when data is normally distributed (exam scores, temperature)
- Median (middle value) — robust to outliers. Use for skewed data (income, house prices, order values)
- Mode (most frequent) — works for categorical data too. Use for finding most common category (popular product, common payment method)
Example: Company salary data — Mean salary = ₹15L (CEO's ₹2Cr pulls it up), Median = ₹8L (actual middle), Mode = ₹6L (most common). Median is most representative here. ⚖️
Q3: How do you handle outliers in data analysis?
Answer: Step-by-step approach:
- Detect — IQR method (
Q1 - 1.5*IQRtoQ3 + 1.5*IQR), Z-score (|z| > 3), visual (box plots) - Investigate — Is it a data error? Genuine extreme value? Different population?
- Decide — Options: Remove (if error), Cap/Winsorize (replace with percentile boundary), Transform (log), Keep (if genuine), Separate analysis
Key principle: Never blindly remove outliers — always document your decision and reasoning. 🎯
Q4: What is correlation and what are its limitations?
Answer: Correlation measures the linear relationship between two variables (range: -1 to +1).
- Pearson's r — linear relationship, requires normality
- Spearman's ρ — monotonic relationship, rank-based, non-parametric
- Kendall's τ — ordinal association, robust for small samples
Limitations:
- Only captures linear relationships (quadratic relationship may show r ≈ 0)
- Correlation ≠ Causation — confounding variables exist
- Sensitive to outliers (Pearson especially)
- Sample size affects significance — large n makes small r "significant"
Always plot your data! Anscombe's quartet shows 4 datasets with same r but very different patterns. 📈
Q5: Explain RFM Analysis and how you would implement it.
Answer: RFM segments customers based on:
- Recency — How recently did they purchase? (lower = better)
- Frequency — How often do they purchase? (higher = better)
- Monetary — How much do they spend? (higher = better)
Implementation:
- Calculate R, F, M values per customer
- Score each on 1-5 scale using quintiles (
pd.qcut) - Combine scores (e.g., "555" = best customer)
- Define segments: Champions (5,5,5), Loyal (4+,4+,*), At Risk (1-2,4+,4+), Lost (1,1,1)
Business impact: Targeted marketing campaigns increase ROI by 3-5x compared to mass campaigns. Champions get exclusive deals, At Risk get win-back offers, New customers get onboarding sequences. 🏆
Q6: How do you determine if a difference between two groups is statistically significant?
Answer: Follow this decision tree:
- Check normality — Shapiro-Wilk test on both groups
- Check variance homogeneity — Levene's test
- Choose test:
- Normal + equal variance → Independent t-test
- Normal + unequal variance → Welch's t-test
- Not normal → Mann-Whitney U test
- 3+ groups → ANOVA (normal) or Kruskal-Wallis (non-normal)
- Interpret: p < 0.05 = significant (reject null hypothesis)
- Report effect size (Cohen's d) — statistical significance ≠ practical significance
from scipy import stats
t_stat, p_value = stats.ttest_ind(group_a, group_b)
# Cohen's d
d = (group_a.mean() - group_b.mean()) / np.sqrt((group_a.std()**2 + group_b.std()**2) / 2)Q7: What is the difference between resample() and groupby() for time series data?
Answer:
| Feature | resample() | groupby() |
|---|---|---|
| Requires | DatetimeIndex | Any column |
| Frequency | 'D', 'W', 'M', 'Q', 'Y' | Manual extraction (dt.month) |
| Missing periods | Creates rows for empty periods | Skips missing |
| Fill methods | ffill, bfill, interpolate | Not built-in |
| Rolling compatible | Yes, directly | Need extra steps |
Use resample() when you want continuous time series with consistent frequency. Use groupby() when you want categorical time grouping (e.g., compare all Januarys across years). ⏰
Q8: How would you present EDA findings to a non-technical stakeholder?
Answer: Key principles:
- Start with the business question — "Here's what we wanted to find out"
- Lead with insights, not methods — "Sales peak on Fridays" not "GroupBy with mean aggregation shows..."
- Use visualizations — bar charts, line trends, pie charts (simple ones)
- Provide context — "Revenue grew 15% MoM, which is 2x industry average"
- End with recommendations — "Based on this, I recommend..."
Structure: Executive Summary → Key Findings (3-5 bullet points) → Supporting Analysis → Recommendations → Appendix (technical details). Always tie numbers back to business impact (revenue, cost, customer satisfaction). 📋
Q9: What are the assumptions of Pearson correlation and what happens when they're violated?
Answer: Assumptions:
- Linearity — relationship should be linear (violation: underestimates strength of curved relationships)
- Normality — both variables approximately normal (violation: unreliable p-values)
- Homoscedasticity — constant variance (violation: biased estimates)
- No outliers — extreme values distort results (violation: inflated/deflated r)
- Continuous data — both variables measured on interval/ratio scale
When violated: Use Spearman's rank correlation (handles non-linearity, ordinal data, outliers) or Kendall's tau (small samples, many ties). Always visualize with scatter plot before computing correlation. 🔗
Q10: How do you handle the "multiple testing problem" in EDA?
Answer: When you perform many statistical tests, the probability of at least one false positive increases. With 20 tests at α=0.05, expected false positives = 1.
Solutions:
- Bonferroni correction — divide α by number of tests (α/n). Conservative but simple
- Holm-Bonferroni — step-down procedure, less conservative
- False Discovery Rate (FDR) — Benjamini-Hochberg procedure, controls proportion of false discoveries
- Pre-registration — decide which tests to run before looking at data
from statsmodels.stats.multitest import multipletests
rejected, p_corrected, _, _ = multipletests(p_values, method='bonferroni')In EDA context: treat findings as hypothesis-generating, not hypothesis-confirming. Validate important findings on held-out data or with domain experts. 🎯
*Next Lesson: Matplotlib →*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Data Analysis with Python.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, data, science, analysis
Related Python Master Course Topics