Linear association
Measure the strength and direction of a linear relationship between two numeric datasets.
SciPy · Function
Computes the Pearson correlation coefficient between two datasets and tests the null hypothesis of non-correlation. It returns the coefficient and a p-value for the selected alternative hypothesis.
pearsonr compares two equally sized datasets, computing their Pearson product-moment correlation and testing the null hypothesis that the underlying distributions are uncorrelated and normally distributed. The returned result exposes the coefficient as statistic and the selected hypothesis-test p-value as pvalue.
scipy.stats.pearsonr(x, y, *, alternative='two-sided', method=None)| Name | Type | Description |
|---|---|---|
x | (N,) array_like | Input array. |
y | (N,) array_like | Input array. |
alternative | {'two-sided', 'greater', 'less'}, optional | Defines the alternative hypothesis. Options are two-sided, greater, and less; the default is two-sided. |
method | ResamplingMethod, optional | Defines the method used to compute the p-value. |
A PearsonRResult with statistic, the Pearson product-moment correlation coefficient, and pvalue, the p-value associated with the chosen alternative.
from scipy.stats import pearsonr
x = [1, 2, 3, 4, 5]
y = [2, 4, 5, 8, 10]
result = pearsonr(x, y)
print(result.statistic)
print(result.pvalue)Computes the sample Pearson correlation and the default two-sided p-value.
Measure the strength and direction of a linear relationship between two numeric datasets.
Test whether observed linear correlation is compatible with an uncorrelated population under the documented assumptions.
Use a one-sided alternative when the scientific question specifies positive or negative correlation in advance.
It returns a Pearson product-moment correlation coefficient and a p-value for testing non-correlation. The coefficient describes the linear relationship, while the p-value indicates how likely an uncorrelated system is to produce a result at least as extreme.
Follow-up: What does a coefficient of -1 mean? It indicates an exact negative linear relationship: as one variable increases, the other decreases exactly.
The alternative argument selects the hypothesis direction. two-sided tests whether the correlation is nonzero, less tests whether it is negative, and greater tests whether it is positive.
Follow-up: When should greater be used? Use it when the planned alternative hypothesis is a positive correlation, rather than selecting it after inspecting the data.
The result has statistic and pvalue attributes. statistic is the Pearson correlation coefficient, and pvalue corresponds to the selected alternative hypothesis.
Follow-up: Why use named attributes instead of positional unpacking? They make the meaning of each returned value explicit and match the documented result object.
scipy.stats.spearmanrscipy.stats.kendalltauscipy.stats.PearsonRResult