Written and maintained by CASRAI Editorial Board
Published
On this page
To run a simple linear regression in SciPy, call scipy.stats.linregress(x, y) with two one-dimensional arrays of equal length. It returns the least-squares slope and intercept, the correlation coefficient (rvalue), a p-value for the slope, and standard errors for both the slope and the intercept. It fits one predictor only; for several predictors use statsmodels OLS. This page is based on the SciPy v1.18 documentation and uses a small worked example whose numbers were generated by running the code under SciPy 1.18.1.
What scipy.stats.linregress is used for in research
The function calculates a linear least-squares regression for two sets of measurements: a predictor x and a response y. Typical uses are a calibration line (instrument signal against known concentration), a dose or time trend with a single explanatory variable, and a quick check of how steeply one measurement changes with another. The search phrases “scipy linear regression” and “linear regression scipy” both refer to this function.
It is deliberately narrow. The documentation describes x and y as two sets of measurements of the same length, so there is no formula interface, no categorical predictors and no second predictor. If your question needs those, see statsmodels OLS. For nonlinear models see curve_fit in SciPy, and for what the slope means as an effect estimate see regression coefficients.
Install or access SciPy
The SciPy project’s install page gives two routes. With pip, run the install inside a virtual environment:
python -m pip install scipy
With conda or mamba, run conda install scipy (or the mamba equivalent); the project recommends the Miniforge distribution for conda and mamba. For new project workflows it also points to uv and pixi. NumPy is installed as a dependency, and you import both:
import numpy as np
from scipy import stats
Step-by-step: fit a line with linregress
- Put the data in two equal-length 1-D arrays. The predictor goes first.
x = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=float) y = np.array([2.1, 2.9, 3.2, 4.8, 5.1, 5.9, 7.2, 7.8]) - Call the function.
res = stats.linregress(x, y) print(res) - Read the attributes by name.
res.slope,res.intercept,res.rvalue,res.pvalue,res.stderrandres.intercept_stderr. - Square the correlation for R².
res.rvalue**2is the coefficient of determination. - Draw the fitted line as
res.intercept + res.slope * xover a scatter of the raw points (see linear regression on a scatter plot).
Running these steps on the example data under SciPy 1.18.1 gave the result below (rounded here for reading).
| Attribute | Value for the example data |
|---|---|
| slope | 0.8310 |
| intercept | 1.1357 |
| rvalue | 0.9919 |
| rvalue**2 (R²) | 0.9839 |
| pvalue (two-sided) | 1.31e-06 |
| stderr (slope) | 0.0434 |
| intercept_stderr | 0.2192 |
Output and how to read it
The function returns a LinregressResult object. Per the SciPy documentation, each field means the following.
- slope and intercept: the fitted line is
intercept + slope * x. - rvalue: the Pearson correlation coefficient. Its square is the coefficient of determination, the share of variance in
yaccounted for by the line. - pvalue: the two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero, using the Wald test with the t-distribution of the test statistic.
- stderr: the standard error of the estimated slope, computed under the assumption of normally distributed residuals.
- intercept_stderr: the standard error of the estimated intercept, under the same assumption.
A small p-value says the data are hard to reconcile with a slope of exactly zero; it does not say the relationship is causal or that a straight line is the right shape. Look at the residuals or the scatter plot before trusting the slope. For the logic behind slope tests see hypothesis testing in linear regression.
Confidence intervals for slope and intercept
linregress returns standard errors rather than intervals, so you build the interval yourself. The SciPy documentation example does this with the t-distribution and n − 2 degrees of freedom:
from scipy.stats import t
tinv = lambda p, df: abs(t.ppf(p / 2, df))
ts = tinv(0.05, len(x) - 2)
print(f"slope (95%): {res.slope:.6f} +/- {ts * res.stderr:.6f}")
print(f"intercept (95%): {res.intercept:.6f} +/- {ts * res.intercept_stderr:.6f}")
For the example data the multiplier ts is 2.4469 (6 degrees of freedom), giving a slope of 0.8310 ± 0.1062 and an intercept of 1.1357 ± 0.5363. For a general explanation of intervals see confidence intervals explained.
One-sided test with the alternative argument
Since SciPy 1.7.0 the function accepts alternative, with values 'two-sided' (the default, slope is nonzero), 'less' (slope is negative) and 'greater' (slope is positive). Only the p-value changes. On the example data, stats.linregress(x, y, alternative='greater').pvalue is 6.57e-07, half the two-sided value, because the fitted slope is positive. Choose the direction before looking at the data.
Missing values with nan_policy
The nan_policy argument accepts 'propagate' (default: the result contains NaN), 'omit' (NaN pairs are dropped) and 'raise' (a ValueError is raised). If you set the fourth example value in y to NaN, the default call returns a slope of nan, while nan_policy='omit' fits the remaining seven pairs and returns 0.8356. Report how many pairs were dropped when you omit values.
Other arguments: axis and keepdims
The signature also carries axis (default 0) and keepdims (default False). Per the documentation, axis=None ravels the input before fitting, so a two-dimensional array is flattened into one long sample rather than fitted column by column; use that only when the cells really are independent pairs. For ordinary work, pass two plain 1-D arrays and leave these at their defaults.
What to report in a methods section
State the function and SciPy version (here scipy.stats.linregress, SciPy 1.18), the number of pairs used and how many were omitted, the slope and intercept with their 95% confidence intervals and how they were computed (t-distribution, n − 2 degrees of freedom), R², and whether the p-value was two-sided. Add a scatter plot with the fitted line so readers can judge linearity themselves. These details let another researcher reproduce the fit exactly from the same data.
Troubleshooting
Unpacking drops intercept_stderr
The result still behaves like a length-5 named tuple for backward compatibility, so slope, intercept, r, p, se = linregress(x, y) works, but that form does not expose intercept_stderr. Use attribute access on the returned object whenever you need the intercept’s standard error, including for the interval above.
Every number is NaN
The default nan_policy='propagate' returns NaN when the input contains NaN. Clean the data deliberately, or pass nan_policy='omit' and record the number of removed pairs.
The slope looks wrong, or the arguments seem swapped
Check the order: linregress(x, y) takes the predictor first. A related robust function, theilslopes, takes (y, x), the opposite order, so copying a call between the two silently regresses the wrong variable on the other.
You need more than one predictor, or a polynomial
linregress is a two-array function. Use statsmodels OLS for multiple predictors, or NumPy’s polynomial tools for a curve of higher degree.
Free alternatives and neighbouring functions
All of the following are open-source Python tools documented by their projects. The table compares the call shapes as the documentation states them; for a hands-on Python statistics overview see scipy.stats for normality tests and t-tests and free statistical software.
| Function | Argument order | What it does | Reports |
|---|---|---|---|
scipy.stats.linregress |
(x, y) | Ordinary least-squares line for one predictor | slope, intercept, rvalue, pvalue, stderr, intercept_stderr |
scipy.stats.theilslopes |
(y, x) | Theil-Sen estimator: median of pairwise slopes, described in the docs as robust linear regression | slope, intercept, low_slope, high_slope (confidence interval for the slope, alpha=0.95 by default) |
numpy.polyfit |
(x, y, deg) | Least-squares polynomial fit; coefficients returned highest power first | coefficients only unless full=True or cov=True |
numpy.polynomial.Polynomial.fit |
(x, y, deg) | Newer NumPy polynomial API, recommended in the NumPy docs for new code; coefficients lowest power first | a Polynomial object |
On the example data, theilslopes(y, x) returns a slope of 0.8155 with a confidence interval of 0.7333 to 0.9500, against linregress’s 0.8310, and np.polyfit(x, y, 1) returns the coefficients [0.8310, 1.1357], slope first because the highest power comes first. The two least-squares routes agree; the median-based Theil-Sen slope differs slightly, as expected for an estimator that does not minimise squared error.
Frequently asked questions
What is the difference between “scipy linear regression” and “linear regression scipy”?
Nothing: both refer to fitting a straight line in SciPy, and in the scipy.stats module that means linregress.
How do I get R-squared from linregress?
Square the rvalue attribute: res.rvalue**2. The documentation notes that the square of the correlation coefficient is the coefficient of determination.
Does linregress give confidence intervals?
No, it gives standard errors. Multiply them by the t critical value with n − 2 degrees of freedom, as shown above.
Can linregress handle multiple regression?
No. It accepts a single predictor. Use statsmodels OLS for several predictors.
Is the p-value one-sided or two-sided?
Two-sided by default, testing whether the slope is zero. Pass alternative='less' or 'greater' for a one-sided test (SciPy 1.7.0 and later).
Sources
- SciPy documentation, scipy.stats.linregress (v1.18.0), read 2026-11-14.
- SciPy documentation, scipy.stats.theilslopes, read 2026-11-14.
- SciPy project, Installing SciPy, read 2026-11-14.
- NumPy documentation, numpy.polyfit, read 2026-11-14.
- Worked-example values: computed by running the code shown on this page with SciPy 1.18.1 and NumPy.
Data: Straight-line fitting functions in SciPy and NumPy: call signatures and returned fields
Compares the documented call signature, argument order and returned quantities of scipy.stats.linregress, scipy.stats.theilslopes and numpy.polyfit, compiled from the projects' official reference pages.
| Function | Call signature (documented) | First positional argument | Returns |
|---|---|---|---|
| scipy.stats.linregress | linregress(x, y, alternative='two-sided', *, axis=0, nan_policy='propagate', keepdims=False) | x (predictor) | slope, intercept, rvalue, pvalue, stderr, intercept_stderr |
| scipy.stats.theilslopes | theilslopes(y, x=None, alpha=0.95, method='separate', *, axis=None, nan_policy='propagate', keepdims=False) | y (response) | slope, intercept, low_slope, high_slope |
| numpy.polyfit | polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False) | x (predictor) | polynomial coefficients, highest power first |
Sources
- scipy.stats.linregress (SciPy v1.18.0) (accessed 2026-11-14)
- scipy.stats.theilslopes (accessed 2026-11-14)
- numpy.polyfit (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







