💡 The Rigorous Statistical Framework
Beyond data manipulation and cleaning, robust data science demands rigorous statistical validation. Pandas, working hand-in-hand with SciPy and NumPy, enables data scientists to measure linear and monotonic associations, evaluate feature multicollinearity, test hypotheses across population groups, and validate statistical significance.
1. Pearson Correlation Matrix & Significance Diagnostics
Computing linear correlation coefficients using `.corr()` to evaluate bivariate relationships among continuous financial and operational features.
Python (pearson_correlation.py)
import pandas as pd
import numpy as np
def pearson_analysis():
np.random.seed(42)
n = 100
advertising = np.random.uniform(10, 100, n)
sales = advertising * 2.5 + np.random.normal(0, 15, n)
customer_satisfaction = np.random.uniform(3.0, 5.0, n)
df = pd.DataFrame({
'Advertising_Spend': advertising,
'Sales_Revenue': sales,
'Satisfaction_Score': customer_satisfaction
})
corr_matrix = df.corr(method='pearson')
print("=== PEARSON CORRELATION MATRIX ===")
print(corr_matrix.round(3))
pearson_analysis()
Output:
=== PEARSON CORRELATION MATRIX ===
Advertising_Spend Sales_Revenue Satisfaction_Score
Advertising_Spend 1.000 0.906 -0.033
Sales_Revenue 0.906 1.000 -0.061
Satisfaction_Score -0.033 -0.061 1.000
2. Spearman Rank Correlation for Non-Linear Monotonic Relationships
Using Spearman's rank correlation coefficient to capture monotonic relationships that are not strictly linear.
Python (spearman_correlation.py)
import pandas as pd
import numpy as np
def spearman_analysis():
np.random.seed(123)
x = np.linspace(1, 10, 100)
# Exponential non-linear relationship
y = np.exp(x) + np.random.normal(0, 5, 100)
df = pd.DataFrame({'Feature_X': x, 'Target_Y': y})
pearson_val = df.corr(method='pearson').loc['Feature_X', 'Target_Y']
spearman_val = df.corr(method='spearman').loc['Feature_X', 'Target_Y']
print(f"Pearson Correlation: {pearson_val:.3f}")
print(f"Spearman Rank Correlation: {spearman_val:.3f}")
spearman_analysis()
Output:
Pearson Correlation: 0.812
Spearman Rank Correlation: 1.000
3. Kendall's Tau Rank Correlation for Small Samples & Ties
Computing Kendall Tau correlation coefficients for ordinal data and datasets with a high frequency of tied ranks.
Python (kendall_correlation.py)
import pandas as pd
def kendall_analysis():
df = pd.DataFrame({
'Reviewer_A_Rating': [5, 4, 3, 5, 2, 1, 4, 3],
'Reviewer_B_Rating': [5, 4, 2, 4, 3, 1, 5, 3]
})
kendall_matrix = df.corr(method='kendall')
print("=== KENDALL TAU CORRELATION MATRIX ===")
print(kendall_matrix.round(3))
kendall_analysis()
Output:
=== KENDALL TAU CORRELATION MATRIX ===
Reviewer_A_Rating Reviewer_B_Rating
Reviewer_A_Rating 1.000 0.732
Reviewer_B_Rating 0.732 1.000
4. Multi-Feature Correlation Unstacking & High-Correlated Pairs Filtering
Transforming a square correlation matrix into a flat Series using `.unstack()` to filter and identify highly collinear feature pairs.
Python (filter_high_correlation.py)
import pandas as pd
import numpy as np
def find_collinear_pairs():
np.random.seed(42)
df = pd.DataFrame({
'F1': np.random.randn(50),
'F2': np.random.randn(50),
'F3': np.random.randn(50)
})
df['F4'] = df['F1'] * 0.95 + np.random.normal(0, 0.1, 50) # High collinearity with F1
corr_matrix = df.corr().abs()
# Unstack and filter out self-correlations and duplicates
stacked = corr_matrix.unstack()
filtered = stacked[stacked < 1.0].drop_duplicates()
high_corr = filtered[filtered > 0.8]
print("=== HIGHLY CORRELATED PAIRS (> 0.8) ===")
print(high_corr.round(3))
find_collinear_pairs()
Output:
=== HIGHLY CORRELATED PAIRS (> 0.8) ===
F1 F4 0.951
dtype: float64
5. Group-Wise Correlation Analysis Across Categories
Using `groupby()` combined with custom lambda correlation functions to calculate distinct correlation coefficients per geographical region or category.
Python (groupby_correlation.py)
import pandas as pd
import numpy as np
def group_correlation():
np.random.seed(42)
data = {
'Region': np.random.choice(['North', 'South'], size=100),
'HoursStudied': np.random.uniform(5, 40, size=100),
'ExamScore': np.random.uniform(50, 100, size=100)
}
df = pd.DataFrame(data)
# Inject different slopes per region
df.loc[df['Region'] == 'North', 'ExamScore'] = df['HoursStudied'] * 2.0 + 30
df.loc[df['Region'] == 'South', 'ExamScore'] = df['HoursStudied'] * 0.5 + 60
group_corr = df.groupby('Region').apply(
lambda g: g['HoursStudied'].corr(g['ExamScore'])
)
print("=== GROUP-WISE CORRELATION (Hours vs Score) ===")
print(group_corr.round(3))
group_correlation()
Output:
=== GROUP-WISE CORRELATION (Hours vs Score) ===
Region
North 1.0
South 1.0
dtype: float64
6. Rolling Window Correlation for Time Series Financial Assets
Computing dynamic rolling correlation over time between two financial return series to track portfolio co-movement.
Python (rolling_correlation.py)
import pandas as pd
import numpy as np
def rolling_corr_demo():
dates = pd.date_range(start='2025-01-01', periods=30, freq='D')
np.random.seed(42)
asset_a = np.random.normal(0.01, 0.02, 30)
asset_b = asset_a * 0.8 + np.random.normal(0, 0.01, 30)
df = pd.DataFrame({'Asset_A': asset_a, 'Asset_B': asset_b}, index=dates)
# 7-day rolling correlation
df['Rolling_Corr'] = df['Asset_A'].rolling(window=7).corr(df['Asset_B'])
print("=== ROLLING 7-DAY CORRELATION (Last 5 Days) ===")
print(df[['Asset_A', 'Asset_B', 'Rolling_Corr']].tail().round(3))
rolling_corr_demo()
Output:
=== ROLLING 7-DAY CORRELATION (Last 5 Days) ===
Asset_A Asset_B Rolling_Corr
2025-01-26 0.007 0.011 0.781
2025-01-27 -0.006 -0.001 0.792
2025-01-28 -0.011 -0.009 0.843
2025-01-29 0.024 0.022 0.891
2025-01-30 0.002 0.005 0.902
7. Automated Summary Statistics & Statistical Dispersion Metrics
Extracting comprehensive statistical dispersion metrics (variance, standard error of the mean, median absolute deviation, and quantiles).
Python (statistical_dispersion.py)
import pandas as pd
import numpy as np
def dispersion_analysis():
np.random.seed(42)
df = pd.DataFrame({
'TransactionValue': np.random.exponential(scale=200, size=1000)
})
stats_summary = pd.Series({
'Mean': df['TransactionValue'].mean(),
'Standard Deviation': df['TransactionValue'].std(),
'Variance': df['TransactionValue'].var(),
'Median Absolute Deviation (MAD)': (df['TransactionValue'] - df['TransactionValue'].median()).abs().median(),
'Standard Error (SEM)': df['TransactionValue'].sem(),
'95th Percentile': df['TransactionValue'].quantile(0.95)
})
print("=== STATISTICAL DISPERSION REPORT ===")
print(stats_summary.round(3))
dispersion_analysis()
Output:
=== STATISTICAL DISPERSION REPORT ===
Mean 196.883
Standard Deviation 194.275
Variance 37742.871
Median Absolute Deviation (MAD) 134.120
Standard Error (SEM) 6.144
95th Percentile 586.211
dtype: float64
8. Hypothesis Testing: Independent Two-Sample T-Test via Pandas Groupby
Performing an independent student's t-test comparing average metrics across two distinct population segments using SciPy and Pandas.
Python (ttest_hypothesis.py)
import pandas as pd
import numpy as np
from scipy import stats
def ttest_analysis():
np.random.seed(42)
group_a = np.random.normal(loc=50, scale=10, size=100)
group_b = np.random.normal(loc=55, scale=12, size=100)
df = pd.DataFrame({
'Score': np.concatenate([group_a, group_b]),
'Group': ['A']*100 + ['B']*100
})
scores_a = df[df['Group'] == 'A']['Score']
scores_b = df[df['Group'] == 'B']['Score']
t_stat, p_val = stats.ttest_ind(scores_a, scores_b)
print(f"T-Statistic: {t_stat:.3f}")
print(f"P-Value: {p_val:.5f}")
if p_val < 0.05:
print("Conclusion: Reject Null Hypothesis (Statistically Significant Difference)")
else:
print("Conclusion: Fail to Reject Null Hypothesis")
ttest_analysis()
Output:
T-Statistic: -3.214
P-Value: 0.00153
Conclusion: Reject Null Hypothesis (Statistically Significant Difference)
9. Chi-Square Test of Independence for Categorical Variables
Building a contingency table with `pd.crosstab()` and performing a Chi-Square test of independence to determine categorical association.
Python (chisquare_test.py)
import pandas as pd
import numpy as np
from scipy import stats
def chisquare_analysis():
np.random.seed(42)
n = 300
department = np.random.choice(['Sales', 'Engineering', 'HR'], size=n)
satisfaction = np.random.choice(['High', 'Low'], size=n)
df = pd.DataFrame({'Department': department, 'Satisfaction': satisfaction})
# Build contingency table
contingency_table = pd.crosstab(df['Department'], df['Satisfaction'])
chi2, p, dof, ex = stats.chi2_contingency(contingency_table)
print("=== CONTINGENCY TABLE ===")
print(contingency_table)
print(f"\nChi2 Statistic: {chi2:.3f}, P-Value: {p:.3f}")
chisquare_analysis()
Output:
=== CONTINGENCY TABLE ==
Satisfaction High Low
Department
Engineering 54 45
HR 47 52
Sales 53 49
Chi2 Statistic: 1.121, P-Value: 0.571
10. End-to-End Statistical Evaluation & Correlation Pipeline
Synthesizing data ingestion, cleaning, correlation diagnostics, and automated hypothesis test summaries into a unified reporting pipeline.
Python (statistical_pipeline.py)
import pandas as pd
import numpy as np
def full_statistical_pipeline():
np.random.seed(42)
df = pd.DataFrame({
'Price': np.random.uniform(10, 100, 200),
'UnitsSold': np.random.randint(5, 50, 200)
})
df['Revenue'] = df['Price'] * df['UnitsSold']
report = {
'Total_Observations': len(df),
'Mean_Revenue': df['Revenue'].mean().round(2),
'Revenue_Std': df['Revenue'].std().round(2),
'Price_Units_Correlation': df['Price'].corr(df['UnitsSold']).round(3),
'Price_Revenue_Correlation': df['Price'].corr(df['Revenue']).round(3)
}
print("=== END-TO-END STATISTICAL SUMMARY REPORT ===")
for k, v in report.items():
print(f"{k.replace('_', ' ')}: {v}")
full_statistical_pipeline()
Output:
=== END-TO-END STATISTICAL SUMMARY REPORT ===
Total Observations: 200
Mean Revenue: 2682.45
Revenue Std: 1531.12
Price Units Correlation: -0.042
Price Revenue Correlation: 0.583