← Back to NumPy Course | Chapter 8: Statistics | Lesson 3 of 6

np.corrcoef()

Correlation says how closely two sets of numbers move together, from -1 to +1.

In this page:

  1. np.corrcoef()
Syntax
python
corr = np.corrcoef(x, y)

np.corrcoef()

np.corrcoef returns a correlation matrix. Values near +1 mean the variables rise together, near -1 mean one rises as the other falls, and near 0 mean no linear relationship. The diagonal is always 1.

Note: The off-diagonal entry [0, 1] is the correlation between the two inputs.

Example: np.corrcoef()

python
import numpy as np

hours = np.array([1, 2, 3, 4, 5])
score = np.array([52, 58, 65, 70, 78])
r = np.corrcoef(hours, score)
print(r.round(3))
print("r =", r[0, 1].round(3))

# Output:
# [[1.    0.998]
#  [0.998 1.   ]]
# r = 0.998
Related Topics
Common Mistakes
  1. Reading correlation as causation
  2. Forgetting it only detects linear relationships
  3. Passing columns when NumPy expects rows
Chapter Summary
  • corrcoef returns a matrix
  • Range is -1 to +1
  • Diagonal is 1
  • Rows are treated as variables
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.