Correlation

Correlation measures the strength and direction of the relationship between two numeric variables - whether they tend to increase together, move in opposite directions, or show no clear relationship at all.

The Correlation Coefficient

Correlation is typically expressed as a number between -1 and +1:

  • +1 - a perfect positive relationship (as one variable increases, so does the other)
  • -1 - a perfect negative relationship (as one variable increases, the other decreases)
  • 0 - no linear relationship between the two variables

Calculating Correlation in Pandas

import pandas as pd

df = pd.DataFrame({
    "StudyHours": [1, 2, 3, 4, 5],
    "Score": [50, 55, 65, 70, 85]
})

print(df["StudyHours"].corr(df["Score"]))   # close to +1

print(df.corr())   # full correlation matrix for all numeric columns

Correlation is Not Causation

A strong correlation between two variables doesn't necessarily mean one causes the other - both could be influenced by a third, unseen factor. For example, ice cream sales and drowning incidents are correlated, but the real cause behind both is simply hot weather.

Before acting on any correlation you find, always ask whether there's a plausible causal explanation, or whether a hidden third variable might be driving both trends independently.

You've Completed This Section

You've now covered the core foundations of Analytics and Exploratory Data Analysis - from the stages of analytics and the CRISP-DM life cycle, through data types, EDA, the four business moment decisions, and correlation. These concepts form the statistical backbone for everything that follows in Data Science.

Computing Pearson's r by Hand

Knowing how the number is built makes it much easier to interpret. Using the study hours example, the Pearson coefficient compares how far each value sits from its mean.

  1. Find the means: study hours average 3, scores average 65.
  2. Subtract the mean from each value. Hours give −2, −1, 0, 1, 2. Scores give −15, −10, 0, 5, 20.
  3. Multiply the paired differences and add them: 30 + 10 + 0 + 5 + 40 = 85.
  4. Square each set of differences and add: hours give 10, scores give 750.
  5. Divide: r = 85 / √(10 × 750) = 85 / 86.6 ≈ 0.98.

The top of the fraction is large and positive because high hours pair with high scores. If high hours had paired with low scores, the products would be negative and r would move towards −1.

Pearson, Spearman or Kendall?

MethodWhat it measuresUse it when
PearsonStrength of a straight-line relationshipBoth variables are numeric and roughly linear, with no extreme outliers
SpearmanWhether the variables rise and fall together in rank orderThe relationship is monotonic but curved, or data is ordinal (ratings, ranks)
KendallAgreement in ordering between pairsSamples are small or contain many tied values

Pandas and SciPy make switching between them a one-word change, and SciPy also returns a p-value that tells you whether the relationship could easily be due to chance in a small sample.

import pandas as pd
from scipy import stats

df = pd.DataFrame({
    "StudyHours": [1, 2, 3, 4, 5],
    "Score": [50, 55, 65, 70, 85]
})

print(df.corr(method="spearman"))          # ranks match perfectly -> 1.0
r, p = stats.pearsonr(df["StudyHours"], df["Score"])
print(round(r, 3), round(p, 4))            # r is about 0.981

Two Traps That Fool Beginners

A zero does not mean "no relationship"

Pearson only detects straight-line patterns. Take x = −2, −1, 0, 1, 2 and y = x², which gives 4, 1, 0, 1, 4. The relationship is perfect, yet Pearson's r is exactly 0 because the curve goes down and then up. Always plot the data before trusting the coefficient.

One outlier can flip the story

Because Pearson uses squared distances, a single extreme point can create a strong correlation where none exists, or hide a real one. If a scatter plot shows one point far from the rest, check whether it is a data entry error, and compare the result with Spearman, which is far less sensitive to outliers.

Using a Correlation Matrix in Exploratory Analysis

With many columns, a heatmap of the correlation matrix quickly shows which features move together.

import seaborn as sns
import matplotlib.pyplot as plt

corr = df.corr(numeric_only=True)
sns.heatmap(corr, annot=True, cmap="coolwarm", vmin=-1, vmax=1)
plt.show()

When two input features are very highly correlated with each other, they carry similar information. In models such as linear regression this causes multicollinearity, so analysts often keep only one of the pair.

Checklist before reporting a correlation

  • Plot a scatter chart first.
  • Pick the method that matches the data type and shape.
  • Check outliers and the sample size.
  • Report the direction, the strength and the p-value, and avoid causal wording.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course