Pandas Correlations
A correlation measures how strongly two numeric columns move together. Do ice-cream sales rise on hot days? Do students who sleep more score higher? df.corr() computes the correlation between every pair of numeric columns in one call.
The correlation coefficient
The result is a number between −1 and 1:
| Value | Meaning |
|---|---|
close to 1 |
strong positive relationship: when one goes up, so does the other |
close to 0 |
no linear relationship |
close to -1 |
strong negative relationship: when one goes up, the other goes down |
As a rough guide, values above 0.7 (or below −0.7) are usually called strong, and values between −0.3 and 0.3 weak.
A first example
Here is a week of data from a beach kiosk:
import pandas as pd
kiosk = pd.DataFrame({
"temp_c": [18, 22, 25, 28, 31, 24, 20],
"ice_creams": [40, 61, 75, 96, 118, 70, 52],
"hot_drinks": [55, 41, 30, 22, 15, 33, 47],
"day_of_week": [1, 2, 3, 4, 5, 6, 7],
})
print(kiosk.corr().round(2)) temp_c ice_creams hot_drinks day_of_week
temp_c 1.00 0.99 -0.99 0.27
ice_creams 0.99 1.00 -0.98 0.28
hot_drinks -0.99 -0.98 1.00 -0.30
day_of_week 0.27 0.28 -0.30 1.00
How to read the matrix:
- Every column correlates perfectly (
1.0) with itself, so the diagonal is all ones. - The matrix is symmetric: the
temp_c/ice_creamsvalue equals theice_creams/temp_cvalue. temp_candice_creamsare almost perfectly positive: hotter days, more ice cream.temp_candhot_drinksare strongly negative: hotter days, fewer hot drinks.day_of_weekis only weakly related to the others: it's just a counter.
Correlation between two columns
To get a single number, call corr() on one Series and pass the other:
import pandas as pd
kiosk = pd.DataFrame({
"temp_c": [18, 22, 25, 28, 31, 24, 20],
"ice_creams": [40, 61, 75, 96, 118, 70, 52],
"hot_drinks": [55, 41, 30, 22, 15, 33, 47],
})
r = kiosk["temp_c"].corr(kiosk["ice_creams"])
print(f"temp vs ice cream: {r:.3f}")
print(kiosk.corr()["temp_c"].sort_values(ascending=False).round(3))temp vs ice cream: 0.994
temp_c 1.000
ice_creams 0.994
hot_drinks -0.995
Name: temp_c, dtype: float64
Picking one column of the matrix and sorting it is a quick way to rank which features relate most to a target, a common first step before building a model.
Text columns and numeric_only
corr() only makes sense for numbers. In pandas 2, if the frame contains text columns you must say so explicitly with numeric_only=True, otherwise you get an error:
import pandas as pd
students = pd.DataFrame({
"name": ["Ada", "Bo", "Cai", "Dee", "Eli", "Fay"],
"sleep_h": [8.0, 6.5, 7.0, 5.5, 9.0, 7.5],
"study_h": [10, 14, 9, 16, 8, 11],
"score": [84, 78, 80, 70, 88, 83],
})
print(students.corr(numeric_only=True).round(2)) sleep_h study_h score
sleep_h 1.00 -0.88 0.98
study_h -0.88 1.00 -0.89
score 0.98 -0.89 1.00
In this made-up class, sleep correlates positively with score, while study hours correlate negatively. That doesn't mean studying hurts! Perhaps students who were behind studied more to catch up. Which leads to the most important rule:
Note: Correlation is not causation. A strong correlation shows that two things move together, not that one causes the other. A hidden third factor (season, income, prior knowledge) can drive both.
Other methods: Spearman and Kendall
The default method="pearson" measures linear relationships. If one value grows with the other but not in a straight line, or the data has outliers, Spearman correlation is more robust. Spearman is simply the Pearson correlation of the ranks (1st, 2nd, 3rd…) instead of the raw values, so you can compute it with rank():
import pandas as pd
growth = pd.DataFrame({
"week": [1, 2, 3, 4, 5, 6, 7, 8],
"users": [10, 20, 40, 80, 160, 320, 640, 1280],
})
print("pearson :", round(growth["week"].corr(growth["users"]), 3))
print("spearman:", round(growth.rank()["week"].corr(growth.rank()["users"]), 3))pearson : 0.85
spearman: 1.0
The users double every week, so the relationship is perfectly monotonic (always increasing) but not linear. Spearman reports a perfect 1.0; Pearson's coefficient is lower because the points don't lie on a straight line.
Tip: The shortcut
df.corr(method="spearman")(or"kendall") gives the same result, but it needs the SciPy library installed (pip install scipy).
Test yourself
What does a correlation of -0.95 between two columns mean?
- No relationship
- A strong relationship where one rises as the other falls
- A weak positive relationship
- One column causes the other
What are the values on the diagonal of df.corr()?
- 0
- 1
- -1
- The column means
Which method is better for a relationship that is always increasing but curved?
- pearson
- spearman
- mean
- cov