Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 19/ 160
01. Python & Data Wrangling

Correlation & Covariance Analysis

Measure linear associations, read correlation matrices, and avoid mistaking correlation for causation.

IntermediatePearson/Spearman · Covariance3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Correlation is a number from −1 to 1 that says how closely two things rise and fall together; it doesn't say one causes the other.

Think of it like…

Two people walking along a road: covariance asks whether they tend to speed up and slow down together; correlation puts that on a standard −1 to +1 scale. They might be in step because they're talking to each other, because of the same hill, or by coincidence, and the number alone can't say which.

Where you’ve seen it

A growth analyst finds ice-cream sales and drowning incidents have r = 0.82 across months. Both rise in summer, so the correlation reflects temperature as a common cause, not a causal link. On the same dataset, the relationship between ad spend and sales is curved (diminishing returns): Pearson r is only 0.45, but Spearman ρ is 0.88, which correctly signals a strong monotonic relationship and prompts a log transform.

Words you’ll hear

Covariance
Average product of deviations from the means; sign shows direction, size depends on units.
Pearson r
Covariance divided by both standard deviations; linear association in [−1, 1].
Spearman ρ
Pearson correlation of the ranks; captures monotonic relationships and resists outliers.
Multicollinearity
Predictors that are strongly correlated with each other, making coefficients unstable.

Visual diagram

Loading interactive diagram

Theory & deep dive

Covariance, Pearson and Spearman

Covariance is the mean of (x − x̄)(y − ȳ): positive when the variables tend to be above their means together, negative when one is high as the other is low. Its size depends on units (height in cm vs m changes it by 100×), so it's hard to compare. Pearson's r divides by the product of standard deviations, giving a unit-free −1 to +1: ±1 is a perfect linear relationship, 0 means no linear relationship. Squared, r² is the share of variance in y explained by a straight-line fit on x.

Pearson assumes a linear relationship and is easily distorted by outliers and heavy tails; Spearman correlates the ranks, so it measures how consistently y rises with x regardless of shape, and one extreme value can't dominate. In pandas: df.corr(numeric_only=True) (Pearson by default), df.corr(method="spearman"), df["a"].corr(df["b"]) and df.cov(). For categorical variables use association measures such as Cramér's V, and for a binary-numeric pair the point-biserial correlation.

Same data, two coefficients

For sales rising with diminishing returns as ad spend grows, df[["ad_spend", "sales"]].corr() gives 0.45 while .corr(method="spearman") gives 0.88, because the ranks line up even though the relationship is curved. Checking both, with a scatter plot, reveals the shape.

Key takeaway: Pearson for linear, Spearman for monotonic; always plot the pair first.

Pitfalls: causation, confounding and many comparisons

A correlation can arise because X affects Y, Y affects X, a third variable drives both (confounding: summer drives ice cream and swimming), or by chance. Time series are especially misleading: two trending series correlate strongly even when unrelated (a spurious correlation), so compare changes or detrend first. Restricting the range of a variable (only high spenders) can shrink the observed correlation, and combining groups can create or reverse it (Simpson's paradox). Establishing causation needs randomised experiments or careful causal methods, not a heatmap.

With 50 features there are 1,225 pairs, so some will look correlated by luck; consider sample size and significance (scipy.stats.pearsonr returns a p-value) and treat exploratory findings as hypotheses. For modelling, find highly correlated predictors (|r| > 0.8 as a rough alarm; variance inflation factors for more rigour) and keep one, combine them, or use regularisation, since multicollinearity makes linear-model coefficients unstable though predictions may still be fine. Never drop a feature solely because its correlation with the target is near zero; it may matter non-linearly or in interaction with others.

Spotting collinear predictors

corr = X.corr().abs(); upper = corr.where(np.triu(np.ones(corr.shape), k=1).astype(bool)); pairs = upper.stack().loc[lambda s: s > 0.85].sort_values(ascending=False) lists predictor pairs worth reviewing, such as height_cm and height_in.

Key takeaway: Look for confounders and trends, expect chance hits, and check collinearity among predictors.

How it works, step by step

Step 1 of 4
Visual

1. Plot before computing

Draw a scatter plot (or hexbin) to see shape, outliers and clusters.

sns.scatterplot(x="ad_spend", y="sales")
Key numbers at this step
Curves
fool Pearson

When to use it & trade-offs

What it is

Covariance measures whether two variables move together, in units that depend on the data's scale. Correlation rescales it to between −1 and +1. Pearson's r captures *linear* association and is sensitive to outliers; Spearman's ρ (and Kendall's τ) use ranks, so they capture any monotonic relationship and resist outliers. A correlation matrix (df.corr(), shown as a heatmap) summarises all pairs. Correlation shows association only, not causation, and it can be zero for strong non-linear relationships.

Why it matters: Correlation is the first tool people reach for to find relationships, pick features and check multicollinearity, and the most misused. Reading r = 0.8 as "X drives Y", trusting r = 0 to mean "unrelated", or ranking features by r on a dataset with outliers are classic mistakes. Interviewers love the "correlation vs causation" question and its follow-ups.

When to reach for it

  • Screening features and detecting multicollinearity
  • Summarising many relationships in a heatmap
  • Generating hypotheses for experiments

When to avoid or be careful

  • Claiming causation from correlation
  • Trusting r = 0 as "no relationship"
  • Correlating two trending time series without detrending

Correlation measures

Pearson r
Best for: Linear relationships between numeric variables

Strengths: Standard; connects to regression and r².

Watch out: Outlier-sensitive; misses curves.

Spearman ρ / Kendall τ
Best for: Monotonic relationships, ordinal data, outliers

Strengths: Rank-based and robust.

Watch out: Less direct link to regression.

Mutual information / Cramér's V
Best for: Non-linear or categorical associations

Strengths: Captures non-linear and categorical dependence.

Watch out: Harder to interpret; no sign.

Interview signals & numbers to know

When this topic comes up

  • “Correlation vs causation”
  • “Pearson vs Spearman”
  • “Two features are highly correlated: what do you do?”
  • Spurious correlations
  • Multicollinearity

Benchmarks & rules of thumb

−1 to +1 -
range of correlation coefficients
r² -
share of variance explained by a linear fit
> 0.8 -
rough threshold for collinearity review

Common mistakes & follow-ups

Common interview mistakes

  • Reporting r = 0.82 between ice cream and drownings as if one caused the other.
  • Dropping a feature with r ≈ 0 to the target when its effect is U-shaped.
  • Correlating cumulative or trending series and finding impressive but meaningless values.

Likely interviewer follow-ups

  • When would Spearman be better than Pearson?
  • Can two variables be strongly related yet have zero correlation?
  • How do you handle two highly correlated predictors?
Interview tip: Give the ice-cream-and-drowning confounder example and the Pearson-vs-Spearman curve example. Two vivid cases beat a definition.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Correlation & Covariance Analysis with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Univariate & Bivariate Analysis
Next topic
Automated Profiling & Reproducible Pipelines