TExcelTAD
Home › SciPy › SciPy Correlation and Regression

SciPy Correlation and Regression

Do taller people weigh more? Does more advertising bring more sales? Correlation measures how strongly two variables move together; regression describes how one changes with the other. scipy.stats provides both, each with a p-value that tells you whether the relationship could be due to chance.

Pearson correlation

The Pearson coefficient r measures linear association. It ranges from −1 (perfect downward line) through 0 (no linear relation) to +1 (perfect upward line):

python · try it yourself
import numpy as np
from scipy import stats

study_hours = np.array([2, 3, 5, 6, 8, 9, 10, 12])
exam_score  = np.array([55, 60, 62, 70, 74, 80, 79, 90])

res = stats.pearsonr(study_hours, exam_score)
print(f"r = {res.statistic:.4f}")
print(f"p = {res.pvalue:.2e}")
ci = res.confidence_interval(0.95)
print(f"95% CI for r: ({ci.low:.3f}, {ci.high:.3f})")
r = 0.9854
p = 7.70e-06
95% CI for r: (0.919, 0.997)
|r| Rough interpretation
0.0 – 0.1 none
0.1 – 0.3 weak
0.3 – 0.7 moderate
0.7 – 1.0 strong

Rank correlations: Spearman and Kendall

Pearson only sees straight lines and is sensitive to outliers. Spearman's ρ and Kendall's τ work on ranks, so they detect any monotonic relationship (always increasing or always decreasing), even a curved one:

python · try it yourself
import numpy as np
from scipy import stats

x = np.arange(1, 11)
y = np.exp(x / 2)          # always increasing, but strongly curved

print(f"Pearson  r   = {stats.pearsonr(x, y).statistic:.4f}")
print(f"Spearman rho = {stats.spearmanr(x, y).statistic:.4f}")
print(f"Kendall  tau = {stats.kendalltau(x, y).statistic:.4f}")
Pearson  r   = 0.8654
Spearman rho = 1.0000
Kendall  tau = 1.0000

The relationship is perfectly monotonic, so both rank correlations are exactly 1, while Pearson's r is lower because the points don't lie on a straight line.

Simple linear regression

linregress() fits the line y = slope · x + intercept by least squares and reports how well it fits:

python · try it yourself
import numpy as np
from scipy import stats

ad_spend = np.array([10, 15, 20, 25, 30, 35, 40])    # thousands
sales    = np.array([120, 135, 160, 172, 190, 205, 228])

fit = stats.linregress(ad_spend, sales)
print(f"sales = {fit.slope:.3f} * spend + {fit.intercept:.3f}")
print(f"R^2   = {fit.rvalue ** 2:.4f}")
print(f"slope std error = {fit.stderr:.3f}, p = {fit.pvalue:.2e}")
print(f"predicted sales at 50k: {fit.slope * 50 + fit.intercept:.1f}")
sales = 3.529 * spend + 84.643
R^2   = 0.9948
slope std error = 0.114, p = 6.53e-07
predicted sales at 50k: 261.1

R² (the square of rvalue) is the share of the variation in y explained by the line.

Seeing the fit

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

rng = np.random.default_rng(11)
temp = rng.uniform(15, 35, size=40)                    # daily max temperature
ice_cream = 20 + 6 * temp + rng.normal(0, 15, size=40) # sales

fit = stats.linregress(temp, ice_cream)
line_x = np.array([15, 35])
plt.scatter(temp, ice_cream, alpha=0.7, label="days")
plt.plot(line_x, fit.intercept + fit.slope * line_x, "r", label="least-squares line")
plt.xlabel("temperature (C)")
plt.ylabel("ice creams sold")
plt.legend()
plt.show()
print(f"slope = {fit.slope:.2f} extra sales per degree, R^2 = {fit.rvalue**2:.3f}")
slope = 5.75 extra sales per degree, R^2 = 0.866

Correlation is not causation

A strong correlation doesn't mean one variable causes the other. Both may be driven by a third factor — ice cream sales and sunburn cases rise together because of sunny weather, not because ice cream causes sunburn:

python · try it yourself
import numpy as np
from scipy import stats

rng = np.random.default_rng(2)
sunshine = rng.uniform(0, 10, size=60)                   # hours of sun (hidden cause)
ice_cream = 50 + 8 * sunshine + rng.normal(0, 6, 60)
sunburn = 2 + 1.5 * sunshine + rng.normal(0, 1.5, 60)

r = stats.pearsonr(ice_cream, sunburn).statistic
print(f"ice cream vs sunburn: r = {r:.3f}")

# Remove the effect of sunshine from both, then correlate what's left
res_ice = ice_cream - stats.linregress(sunshine, ice_cream).intercept \
          - stats.linregress(sunshine, ice_cream).slope * sunshine
res_sun = sunburn - stats.linregress(sunshine, sunburn).intercept \
          - stats.linregress(sunshine, sunburn).slope * sunshine
print(f"after removing sunshine: r = {stats.pearsonr(res_ice, res_sun).statistic:.3f}")
ice cream vs sunburn: r = 0.915
after removing sunshine: r = -0.017

Once the shared cause is removed, almost nothing is left of the correlation. This "correlate the residuals" trick is called partial correlation.

Tip: Always plot your data before trusting a correlation coefficient. Very different scatter plots — a curve, a cluster with one outlier, two separate groups — can all give the same r.

Test yourself

What does a Pearson correlation of r = -0.9 indicate?

  1. No relationship
  2. A strong negative linear relationship
  3. A weak positive relationship
  4. That one variable causes the other

Which correlation detects any monotonic relationship, even a curved one?

  1. Pearson
  2. Spearman
  3. linregress slope
  4. Covariance

In linregress results, what is R²?

  1. The slope squared
  2. rvalue ** 2: the share of variation in y explained by the line
  3. The p-value squared
  4. The intercept