The Pearson correlation coefficient ranges from -1, a perfect negative linear relationship, to 1, a perfect positive linear relationship, with 0 indicating no linear relationship at all. np.corrcoef(x, y) returns a 2x2 matrix, since correlating two variables produces a correlation of each with itself, always exactly 1, on the diagonal, and with the other, the off-diagonal values, which are identical to each other, since correlation is symmetric. It specifically measures linear relationships — two variables can be strongly related in a non-linear way, like a perfect parabola, while still showing a correlation coefficient near 0.
1Understanding np.corrcoef()
The Pearson correlation coefficient ranges from -1, a perfect negative linear relationship, to 1, a perfect positive linear relationship, with 0 indicating no linear relationship at all. np.corrcoef(x, y) returns a 2x2 matrix, since correlating two variables produces a correlation of each with itself, always exactly 1, on the diagonal, and with the other, the off-diagonal values, which are identical to each other, since correlation is symmetric. It specifically measures linear relationships — two variables can be strongly related in a non-linear way, like a perfect parabola, while still showing a correlation coefficient near 0.
A correlation coefficient near 0 doesn't mean two variables are unrelated — it only means they have no strong linear relationship; a perfectly curved, non-linear relationship can still show a correlation near 0 despite being a very predictable relationship.
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])
print(np.corrcoef(x, y))2Practical Example
Here is a real-world application of np.corrcoef() showing how it is used in production NumPy code.
import numpy as np
hours_studied = np.array([1, 2, 3, 4, 5])
test_scores = np.array([50, 55, 65, 70, 90])
correlation = np.corrcoef(hours_studied, test_scores)[0, 1]
print(round(correlation, 3))3Best Practices
Follow these guidelines when working with np.corrcoef():
1. Remember correlation measures only linear relationships — plot the data or check for non-linear patterns before concluding two variables are unrelated based on a low correlation coefficient alone
2. Extract the specific off-diagonal value when you only need the correlation between two variables, rather than reading the whole matrix
3. Never assume correlation implies causation — a high correlation coefficient only describes a statistical relationship, not that one variable causes changes in the other
Tip: A correlation coefficient near 0 doesn't mean two variables are unrelated — it only means they have no strong linear relationship; a perfectly curved, non-linear relationship can still show a correlation near 0 despite being a very predictable relationship.
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])
print(np.corrcoef(x, y))