Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
Researchers reach for numpy.gradient when they have measurements sampled on a grid or at timestamps and need an estimate of the rate of change. After reading this you should be able to call it with the right spacing, choose edge_order, and read the output. Checked against the NumPy 2.5 reference (numpy.org, 2026-11-08) and run on NumPy 2.5.1.
Short answer: np.gradient(f) returns finite-difference estimates of the derivative of the sampled array f, one value per input sample, with the same shape as f. Interior points use second-order accurate central differences; boundaries use first- or second-order one-sided differences. It assumes unit spacing unless you pass the sample spacing or the coordinates.
What it is used for in research
The function turns discretely sampled data into a numerical derivative: velocity from positions, a rate of temperature change from readings, slopes of an image or a 2-D field. It does not fit a model. It differences the samples you give it, so it works on any array without an analytical formula. For fitting a curve first, see the NumPy polyfit guide; for building coordinate grids for 2-D fields, see NumPy meshgrid.
How to install or access it
NumPy’s install page (numpy.org/install) gives pip install numpy, or conda install numpy inside an activated conda environment. Verify with:
import numpy as np
print(np.__version__)
Step-by-step task
The signature in the reference is numpy.gradient(f, *varargs, axis=None, edge_order=1).
Arguments
| Argument | Meaning (per the NumPy reference) |
|---|---|
f |
array_like; N-dimensional array of samples of a scalar function. |
*varargs |
Sample spacing. Default is unit spacing. Accepted forms: one scalar for all dimensions; N scalars, one per dimension; N coordinate arrays whose length matches the corresponding dimension; or a mix of these. If axis is given, the number of varargs must equal the number of axes. |
edge_order |
{1, 2}, default 1. Order of accuracy of the differences at the boundaries. |
axis |
None (default, all axes), an int, or a tuple of ints. Negative values count from the last axis. |
Steps
- Put your samples in a NumPy array (
f) and, if sampling is not unit-spaced, the coordinates in another array of the same length. - Call
np.gradient(f, x)for coordinates, ornp.gradient(f, h)for a constant spacingh. - Choose
edge_order=2if you want second-order accuracy at the two end points (it needs at least three samples). - For arrays with more than one dimension, use
axisto restrict the result to the dimensions you need.
Worked example: uneven time stamps
The calls below reproduce the NumPy reference examples; the output was confirmed by running them on NumPy 2.5.1.
import numpy as np
f = np.array([1, 2, 4, 7, 11, 16])
np.gradient(f) # array([1. , 1.5, 2.5, 3.5, 4.5, 5. ])
np.gradient(f, 2) # array([0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ])
x = np.array([0., 1., 1.5, 3.5, 4., 6.])
np.gradient(f, x) # array([1. , 3. , 3.5, 6.7, 6.9, 2.5])
The same values give different rates depending on what you pass for spacing. With no spacing argument the function treats every step as 1; with x it uses the real gaps, so the third result is the rate of change per unit of x. For research data sampled at irregular times, always pass the time array. The NumPy reference states that the uneven-spacing formula was derived assuming f is three times continuously differentiable.
Checking edge accuracy with edge_order
Take f = x**2 on x = np.arange(5). The exact derivative 2x is 0, 2, 4, 6, 8. The reference shows:
x = np.arange(5)
f = x**2
np.gradient(f, edge_order=1) # array([1., 2., 4., 6., 7.])
np.gradient(f, edge_order=2) # array([0., 2., 4., 6., 8.])
The interior values are already exact here; edge_order=2 also recovers the two end values, while the default is off by 1 at each end. A known-answer test on a function whose derivative you can write down is a quick way to confirm your call before applying it to measurements.
Two or more dimensions
a = np.array([[1, 2, 6], [3, 4, 5]])
np.gradient(a)
# (array([[ 2., 2., -1.],
# [ 2., 2., -1.]]),
# array([[1. , 2.5, 4. ],
# [1. , 1. , 1. ]]))
np.gradient(a, axis=0)
# array([[ 2., 2., -1.],
# [ 2., 2., -1.]])
Output and how to read it
- For a 1-D input you get one array; for N dimensions you get a tuple of N arrays, in axis order (axis 0 first). Each has the same shape as
f. - With
axisset to a single int, a single array is returned (as in the example above). - Units of the result are the units of
fdivided by the units of the spacing or coordinates (editorial interpretation: this follows from differencing and is not a quoted statement of the reference). - Interior points are central differences, second-order accurate; for even spacing the formula is (f(xi+1) − f(xi−1)) / (2h) plus a term of order h². Boundary values are one-sided.
- Editorial caution: differencing amplifies measurement noise, because it subtracts neighbouring noisy values. Compare the output with the raw series before drawing conclusions.
Troubleshooting
| Symptom | Cause and fix (reproduced on NumPy 2.5.1) |
|---|---|
ValueError: when 1d, distances must match the length of the corresponding dimension |
A coordinate array does not have the same length as the matching axis of f. Pass an array of equal length. |
TypeError: invalid number of arguments |
The number of spacing arguments does not match the number of axes (for example three spacings for a 2-D array). Give one scalar, or one per axis. |
ValueError: Shape of array too small to calculate a numerical gradient, at least (edge_order + 1) elements are required. |
Too few samples along an axis; a single-sample array raises this at the default edge_order=1. |
| Results look like “per sample”, not “per unit time” | No spacing was passed, so unit spacing was assumed. Pass the step size or the coordinate array. |
| Integer input, float output | The examples above show integer input returning floating-point values. |
Free alternatives
| Option | Note |
|---|---|
numpy.diff |
Differences between neighbouring samples; the result is one element shorter than the input, and you divide by the spacing yourself. |
numpy.polyfit |
Fit a polynomial, then differentiate it analytically; see the NumPy polyfit guide. |
Both are part of NumPy. Related NumPy array functions are covered in the NumPy histogram and NumPy normalize guides.
FAQ
What does np.gradient return?
An array (or a tuple of arrays, one per dimension) with the same shape as the input, holding the estimated derivative at every sample.
Does np.gradient assume equal spacing?
It assumes unit spacing by default. Pass a scalar for equal spacing or a coordinate array for uneven spacing.
What does edge_order change?
Only the boundary points: 1 uses first-order one-sided differences, 2 uses second-order. The interior is unchanged.
How do I take the gradient along one axis only?
Pass axis as an int, for example np.gradient(a, axis=0).
Sources
- NumPy reference, numpy.gradient, read 2026-11-08.
- NumPy, Installing NumPy, read 2026-11-08.







