Written and maintained by CASRAI Editorial Board
Last updated
Short answer: NumPy has no function called numpy.corr. The function people mean is numpy.corrcoef, which returns the matrix of Pearson product-moment correlation coefficients. Calling np.corr(...) raises an AttributeError; call np.corrcoef(...) instead. This guide is for researchers and analysts who have a table of measurements in Python and need a correlation matrix, and it covers the one mistake that most often gives a wrong answer without any error: the rowvar orientation.
What numpy.corrcoef is used for in research
Pearson correlation measures the strength of the linear association between two quantitative variables, from -1 (perfect negative) to +1 (perfect positive). numpy.corrcoef computes it for every pair of variables you give it at once, so one call yields the whole matrix you would put in a descriptive-statistics table. It does not give a p-value or confidence interval; for those see the alternatives table below. For the concepts behind the number, read types of correlation and scatterplot interpretation, and remember that a correlation alone does not make a correlational study causal.
Install or access
NumPy’s install page (numpy.org/install, read 2026-11-08) lists these official routes: pip install numpy, conda install numpy (defaults or conda-forge channel), uv pip install numpy and pixi add numpy. It recommends working inside a virtual environment, for example one created with python -m venv my-env. Confirm the install:
import numpy as np
print(np.__version__)
Step-by-step: a correlation matrix with np.corrcoef
The signature in the current NumPy reference is numpy.corrcoef(x, y=None, rowvar=True, *, dtype=None).
- Import NumPy.
import numpy as np - Arrange the data so each variable is one row. By default (
rowvar=True) each row ofxis a variable and each column is an observation.x = np.array([[1, 2, 3, 4, 5], [2, 4, 5, 4, 5], [5, 4, 3, 2, 1]], dtype=float) - Call the function.
R = np.corrcoef(x) - Read the result. This example returns a 3 x 3 matrix (rounded to four decimals when run locally with NumPy 2.5.1):
[[ 1. 0.7746 -1. ] [ 0.7746 1. -0.7746] [-1. -0.7746 1. ]] - Optionally pass a second set with
y.yhas the same shape asx; the documentation states that it is treated as additional variables, and the NumPy example with two 3 x 3 arrays returns a 6 x 6 matrix. Stack your variables into one array instead when you can, so every pair appears in a single matrix.
The rowvar pitfall: samples as rows
Most research datasets are stored the other way round: one row per participant or sample, one column per variable. With the default rowvar=True, NumPy treats every row as a variable, so no error is raised and you receive a participant-by-participant matrix instead of a variable-by-variable one. The NumPy reference states that rowvar=False makes each column a variable and each row an observation.
d = np.array([[1, 5], [2, 4], [3, 3], [4, 2], [5, 1], [6, 0]], dtype=float) # 6 samples, 2 variables
np.corrcoef(d).shape # (6, 6) -> correlations between samples (wrong question)
np.corrcoef(d, rowvar=False) # 2 x 2 -> correlations between the two variables
Quick check: the matrix side length must equal the number of variables. If you have 6 samples and 2 variables and get a 6 x 6 matrix, flip rowvar or transpose with d.T.
Output and how to read it
- The result
Ris a square ndarray. Per the documentation,R[i, j] = C[i, j] / sqrt(C[i, i] * C[j, j]), whereCis the covariance matrix (seenumpy.cov). - Values lie between -1 and 1 inclusive. The matrix is symmetric and its diagonal is 1 (a variable correlates perfectly with itself).
- The documentation warns that because of floating-point rounding the result may not be exactly Hermitian and the diagonal may not be exactly 1; real and imaginary parts are clipped to the interval [-1, 1]. Round for reporting rather than testing equality with 1.
- The
dtypeargument (new in NumPy 1.20) sets the result type, with at least float64 precision. - Report the coefficient with the sample size. A coefficient is a descriptive statistic;
corrcoefsupplies no significance test.
Troubleshooting
AttributeError: module ‘numpy’ has no attribute ‘corr’
The function name is corrcoef. The name corr is a method on pandas objects (DataFrame.corr, Series.corr), which is likely where the habit comes from.
A matrix of the wrong size
See the rowvar section above: the size should equal the number of variables.
nan in the output
In a local run with NumPy 2.5.1, a constant variable (for example np.corrcoef([1, 2, 3], [2, 2, 2])) produced nan entries and a RuntimeWarning, because a variable with zero variance has no defined correlation. A missing value (np.nan) in an input likewise produced nan in that run. The NumPy reference page does not describe missing-value handling, so remove or impute missing observations deliberately before calling it, and check your own output.
Need a p-value or confidence interval
corrcoef returns neither. Use scipy.stats.pearsonr (below).
Free alternatives and related functions
| Function | Returns | Notes from the official documentation |
|---|---|---|
numpy.corrcoef(x, y=None, rowvar=True, *, dtype=None) |
Correlation matrix (ndarray) | Pearson product-moment coefficients; rows are variables by default. |
scipy.stats.pearsonr(x, y, *, alternative='two-sided', method=None, axis=0) |
Result object with statistic and pvalue; confidence_interval(confidence_level, method) method |
Use when you need a p-value or confidence interval for one pair. Constant input gives a ConstantInputWarning and nan. The SciPy page cautions that zero correlation does not imply independence unless the pair is jointly normal. |
pandas.DataFrame.corr |
Correlation matrix (DataFrame) | A pandas method, not part of NumPy; see the pandas documentation for its arguments. |
For a single pair, pearsonr(x[0], x[1]) on the example above returns the same coefficient as the matrix (0.7746), plus a two-sided p-value of about 0.124 with n = 5 in a local run under SciPy 1.18.0. Related NumPy how-tos on this site: numpy polyfit for fitting a line to the same variables and numpy percentile for distribution summaries.
FAQ
Is there a numpy.corr function?
No. Use numpy.corrcoef; np.corr raises an AttributeError.
Does numpy.corrcoef compute Pearson or Spearman correlation?
Pearson. The NumPy reference describes it as returning Pearson product-moment correlation coefficients. For rank correlation use a different function, such as one from scipy.stats.
How do I get the correlation between just two variables?
Call np.corrcoef(a, b) and read the off-diagonal element [0, 1]; the result is a 2 x 2 matrix.
Why do I get a huge matrix?
Your observations are probably in rows while rowvar is True. Set rowvar=False.
Sources
- NumPy documentation, numpy.corrcoef (stable), read 2026-11-08.
- NumPy, Installing NumPy, read 2026-11-08.
- SciPy documentation, scipy.stats.pearsonr, read 2026-11-08.







