DS Correlation
Correlation measures how strongly two numeric variables move together in a straight-line pattern. The usual measure is Pearson's correlation coefficient, written r, which always lies between −1 and +1.
| r | Meaning |
|---|---|
| +1 | perfect positive line: when x rises, y rises exactly proportionally |
| around +0.7 to +0.9 | strong positive relationship |
| around +0.3 | weak positive relationship |
| 0 | no linear relationship |
| negative values | as x rises, y tends to fall |
| −1 | perfect negative line |
What r looks like
Seeing is the best way to calibrate your intuition. The example simulates four pairs of variables with different correlations:
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(3)
x = rng.normal(0, 1, 200)
noise = rng.normal(0, 1, 200)
cases = {
"strong +": x + 0.3 * noise,
"weak +": x + 2.5 * noise,
"none": noise,
"strong -": -x + 0.5 * noise,
}
fig, axes = plt.subplots(1, 4, figsize=(12, 3), sharey=True)
for ax, (name, y) in zip(axes, cases.items()):
r = np.corrcoef(x, y)[0, 1]
ax.scatter(x, y, s=8)
ax.set_title(f"{name}: r = {r:.2f}")
plt.tight_layout()
plt.show()
for name, y in cases.items():
print(f"{name:9} r = {np.corrcoef(x, y)[0, 1]:.2f}")strong + r = 0.96
weak + r = 0.41
none r = 0.03
strong - r = -0.90
np.corrcoef(x, y) returns a 2 × 2 matrix; the off-diagonal entry [0, 1] is the correlation between x and y.
How r is computed
Pearson's r is the average product of the two variables' z-scores (values expressed as "how many SDs from the mean"). When both are above their means together, or below together, the products are positive; when one is high while the other is low, they are negative.
import numpy as np
temp = np.array([24.1, 15.4, 26.3, 22.1, 6.4, 29.4, 23.8, 24.4, 7.3, 15.7])
rides = np.array([414, 298, 439, 405, 254, 523, 497, 428, 209, 368])
z_temp = (temp - temp.mean()) / temp.std(ddof=1)
z_rides = (rides - rides.mean()) / rides.std(ddof=1)
r_manual = (z_temp * z_rides).sum() / (len(temp) - 1)
print("manual r: ", round(r_manual, 4))
print("np.corrcoef:", round(np.corrcoef(temp, rides)[0, 1], 4))manual r: 0.9472
np.corrcoef: 0.9472
Correlation in pandas
On a DataFrame, s1.corr(s2) gives the correlation between two columns. Let's measure how each weather variable relates to rides over all 60 days:
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
for col in ["temp_c", "rain_mm", "humidity"]:
print(f"corr(rides, {col:8}) = {bikes['rides'].corr(bikes[col]):.3f}")corr(rides, temp_c ) = 0.852
corr(rides, rain_mm ) = -0.410
corr(rides, humidity) = 0.059
- Temperature: strong positive (≈ 0.85).
- Rain: moderate negative (≈ −0.41) — wet days are quieter.
- Humidity: almost zero — no linear relationship in this data.
Correlation only sees straight lines
r captures linear association. A perfectly predictable but curved relationship can have r near 0. Suppose riders avoid both cold and very hot days:
import numpy as np
temp = np.linspace(0, 40, 41)
rides = 500 - (temp - 20) ** 2 # peaks at 20 °C, falls on both sides
print("r =", round(np.corrcoef(temp, rides)[0, 1], 3))
print("rides at 0, 20, 40 °C:", rides[0], rides[20], rides[40])r = 0.0
rides at 0, 20, 40 °C: 100.0 500.0 100.0
The relationship is perfect, yet r is 0. That's why you should always plot before trusting a correlation coefficient. Outliers can mislead in the opposite direction too: a single extreme point can create a large r in otherwise unrelated data.
Tip: For monotonic but curved relationships (always rising, but not in a straight line), use Spearman's rank correlation:
s1.corr(s2, method="spearman").
Test yourself
Which correlation describes the strongest relationship?
- 0.45
- -0.82
- 0.10
- 0.70
r between rain and rides is about −0.41. What does that mean?
- Rain causes 41 % fewer rides
- Wetter days tend to have fewer rides (moderate negative linear relationship)
- There is no relationship
- 41 days were rainy
A scatter plot shows a clear U-shape, but r ≈ 0. What's the best conclusion?
- The variables are unrelated
- There is a strong non-linear relationship that r can't capture
- The data has an error
- r should be −1