Skip to main content
v2026.11,986 entries · CC-BY 4.0

NumPy diff: np.diff Syntax, Axis, n and prepend

How np.diff works: n, axis, prepend and append, output shape and dtype rules, the unsigned-integer trap, and alternatives such as np.gradient.

Written and maintained by CASRAI Editorial Board

Published

On this page

numpy.diff (written np.diff after import numpy as np) calculates the n-th discrete difference of an array along one axis. With the defaults, the first difference is out[i] = a[i+1] - a[i], so an input of length 5 returns an output of length 4. Higher differences are produced by applying the function recursively. The full signature in the NumPy 2.5 manual is numpy.diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>). This guide covers what each argument does, a worked example on research-style readings, the output rules (shape, data type) that surprise people, and when np.ediff1d, np.gradient or pandas Series.diff is the better tool.

Ask CASRAI · free to tryQuestion about this guide? Ask CASRAI answers with linked sources. 2 free questions a day, no account.

Ask your first question freeSubscribe

What np.diff is used for in research

A difference turns a sequence of values into a sequence of changes. In research data that usually means one of three jobs:

  • Change between successive readings. Sensor values, instrument outputs or cell counts recorded at consecutive time points become step changes, which makes jumps and drifts visible.
  • Intervals between events. Applied to an array of timestamps stored as datetime64, the function returns the gaps as timedelta64 values, which is the quickest way to check whether sampling was regular.
  • Removing a trend before time-series analysis. A first difference (n=1) or second difference (n=2) is a common step in preparing a series, and np.diff does the arithmetic. Whether differencing is appropriate for a given model is a methods decision outside this page.

It computes differences between neighbouring samples only. It does not know the spacing of the samples. If your samples are unevenly spaced and you need a rate of change per unit time, divide by the time differences yourself (a second np.diff on the time array) or use np.gradient, covered below. For a related MATLAB view of the same operation, see diff in MATLAB.

Install or access

NumPy is distributed through the official NumPy install page (numpy.org/install). The documented routes are:

  • pip: pip install numpy
  • conda: conda create -n my-env, then conda activate my-env, then conda install numpy
  • Virtual environment with pip: python -m venv my-env, then source my-env/bin/activate on macOS and Linux or my-envScriptsactivate on Windows, then pip install numpy

NumPy is free, open-source software. No separate installation is needed for np.diff; it is part of the main namespace. The examples below use import numpy as np.

Step-by-step: differencing a series of readings

The example uses a small, made-up series of hourly cell counts so the output can be checked by hand. It is an illustrative series, not a measured dataset.

  1. Create the array. counts = np.array([120, 135, 150, 148, 170])
  2. Take the first difference. np.diff(counts) returns array([15, 15, -2, 22]). Each value is the next reading minus the current one: 135 − 120 = 15, 150 − 135 = 15, 148 − 150 = −2, 170 − 148 = 22.
  3. Take a higher difference with n. np.diff(counts, n=2) returns array([0, -17, 24]). This is the first-difference array differenced again: 15 − 15 = 0, −2 − 15 = −17, 22 − (−2) = 24. With n=0 the input is returned as it is.
  4. Keep the original length with prepend. np.diff(counts, prepend=0) returns array([120, 15, 15, -2, 22]). The scalar is expanded to length 1 along the axis and placed before the data, so the first output is 120 − 0. The same idea works with append at the other end.
  5. Difference a two-dimensional array along an axis. Suppose rows are two instruments and columns are time points: x = np.array([[120, 135, 150, 148], [90, 92, 99, 101]]). The default axis=-1 differences along each row, so np.diff(x) returns array([[15, 15, -2], [2, 7, 2]]), shape (2, 3). Setting axis=0 differences between the rows instead, giving array([[-30, -43, -51, -47]]), shape (1, 4).
  6. Difference timestamps. The manual’s example builds dates with np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64); np.diff on that array returns array([1, 1], dtype='timedelta64[D]'), one day between each pair.
  7. Undo the differencing if you need to. Because the output of step 4 starts with the first value minus zero, np.cumsum(np.diff(counts, prepend=0)) gives back [120, 135, 150, 148, 170]. The NumPy manual lists cumsum under See also for this function.

Steps 2 to 5 follow the patterns in the NumPy manual (a 1-D array differenced with n=1 and n=2, and a 2-D array differenced along both axes) with different numbers, so you can check each result by hand; step 6 is taken from the manual.

Arguments in detail

a: the input

a is any array_like. Lists work, because NumPy converts them.

n: how many times to difference

The default is 1. Each extra pass shortens the result by one element along the axis, and the manual states that the output shape equals the input shape except along axis, where it is smaller by n.

axis: which direction

The default is the last axis. For a table laid out as rows = samples and columns = variables, you almost always want axis=0 to difference each variable down the rows; with the default you would instead be subtracting neighbouring columns. Checking x.shape before and after is the fastest way to confirm you differenced the direction you intended.

prepend and append: padding before differencing

These add values along the axis before the differences are computed. Scalars are expanded to length 1 along the axis with the input’s shape on all other axes. Anything that is not a scalar must have the same dimensions and shape as a except along axis.

Output and how to read it

The return value is an ndarray. Its shape matches the input except along the differenced axis, where it is smaller by n. Its data type is the type of the difference of two elements of the input, which has three consequences worth knowing.

  • Position. out[i] describes the change from a[i] to a[i+1]. If you attach the output to the original time axis, the change belongs to the interval between two time points, not to either point, and the output has one fewer value.
  • Sign. A negative value is a decrease from one reading to the next (the −2 in the example above).
  • Datetimes. datetime64 input yields timedelta64 output, as in step 6.

The manual also states two type-specific behaviours, covered under troubleshooting: boolean arrays keep their type, and unsigned integers stay unsigned.

Troubleshooting

Unsigned integers give a value like 255

The manual’s example is u8 = np.array([1, 0], dtype=np.uint8). Then np.diff(u8) returns array([255], dtype=uint8), because 0 − 1 cannot be negative in an unsigned type and wraps around. The documented fix is to cast first: u8.astype(np.int16) followed by np.diff returns array([-1], dtype=int16). Image data and some instrument exports are stored as uint8 or uint16, so cast to a signed type (or float) before differencing any such data.

Boolean input returns booleans, not counts

For a boolean array the result is also boolean: False where consecutive values are equal and True where they differ, according to the manual. To find where a state changes, that is exactly what you want. To count changes, sum the result.

The output is shorter than the input

This is by design. Use prepend or append to pad (step 4), or slice the other arrays you are aligning with so they have the same length, for example with the techniques in NumPy slicing.

Differences are along the wrong direction

If a 2-D result has the wrong shape, you probably used the default axis=-1 when the data runs down the rows. Pass axis=0 explicitly.

prepend or append is rejected

The manual requires non-scalar padding to match the input’s dimensions and shape except along the axis. For a 2-D array differenced along axis=0, a padding array needs the same number of columns as the data.

Rate of change comes out wrong for irregular sampling

np.diff ignores spacing. Divide by the differences of the time array, or use np.gradient with the coordinates supplied (next section).

All of the tools below are free and open source. The data table that follows this body compares their signatures and output rules. In plain terms:

Need Use What the documentation says
Successive differences along an axis, any dimensions np.diff Output is smaller by n along the axis; prepend and append supported.
Differences of a flattened array, with values added at the ends np.ediff1d(ary, to_end=None, to_begin=None) The input is flattened first and the result is always 1-D, loosely ary.flat[1:] - ary.flat[:-1].
A derivative estimate with the same shape as the input np.gradient Second-order accurate central differences in the interior, first- or second-order one-sided differences at the boundaries; accepts sample spacing or coordinates.
Differences inside a pandas Series or DataFrame Series.diff(periods=1) Equivalent to self - self.shift(periods); leading positions are filled with a missing value.
Rebuilding values from differences np.cumsum Listed under See also in the np.diff manual page.

np.ediff1d

For the example array [1, 2, 4, 7, 0], np.ediff1d returns [1, 2, 3, -7], the same as np.diff. They diverge on 2-D input: the manual’s np.ediff1d([[1, 2, 4], [1, 6, 24]]) returns the flat array [1, 2, -3, 5, 18], which includes the jump from the end of one row to the start of the next, whereas np.diff would difference each row separately. to_begin and to_end add values at the ends, for example np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99])) gives [-99, 1, 2, 3, -7, 88, 99].

np.gradient

Use it when you want a rate of change at each sample point and the same number of values back. Its varargs argument accepts a scalar spacing, one spacing per dimension, or arrays of coordinates, so uneven sampling can be handled directly; edge_order (1 or 2) sets the accuracy at the boundaries. See NumPy gradient for a full walk-through.

pandas Series.diff

In pandas, Series.diff(periods=1) compares each value with the one periods rows back and accepts negative values to compare with following rows. Because the leading positions are filled with a missing value, NumPy integer dtypes are cast to floating and NumPy bool to object; boolean dtypes use xor rather than subtraction. For the underlying shift operation, see pandas shift. If you need to realign values by moving them rather than subtracting, NumPy roll is the NumPy counterpart.

Frequently asked questions

What does np.diff do?

It returns the n-th discrete difference along a given axis: out[i] = a[i+1] - a[i] for the first difference, applied recursively for higher orders (NumPy 2.5 manual, read 2026-11-13).

Why is the np.diff output shorter than the input?

Each difference uses two neighbouring elements, so the result is smaller than the input by n along the differenced axis. Use prepend or append to compensate.

How do I difference along columns or rows?

Set axis. The default axis=-1 works along the last axis (across the columns of each row); axis=0 works down the rows.

Why does np.diff return 255 for unsigned integers?

Unsigned types cannot hold negative values, so the difference wraps around. Convert with astype to a signed type such as int16 first.

What is the difference between np.diff and np.gradient?

np.diff returns successive differences and shortens the array; np.gradient returns an estimate of the derivative with the same shape as the input and can use the sample spacing.

What is the difference between np.diff and np.ediff1d?

np.ediff1d flattens its input and always returns a 1-D array; np.diff keeps the dimensions and differences along a chosen axis.

How do I compute the difference between datetimes?

Pass a datetime64 array to np.diff; the output is timedelta64.

Sources

Data: Difference functions in NumPy and pandas: signatures and output rules

Compares four free Python functions that compute successive differences (numpy.diff, numpy.ediff1d, numpy.gradient, pandas Series.diff) by signature, output shape and handling of the ends, compiled from the official NumPy and pandas reference pages.

Period covered: 2026.

Difference functions in NumPy and pandas: signatures and output rules
FunctionSignatureOutput shape relative to inputHandling of ends
numpy.diffnumpy.diff(a, n=1, axis=-1, prepend=, append=)Same as input except along axis, where it is smaller by nprepend and append add values along the axis before differencing
numpy.ediff1dnumpy.ediff1d(ary, to_end=None, to_begin=None)Always 1-D; input is flattened firstto_begin and to_end add values at the ends
numpy.gradientnumpy.gradient(f, *varargs, axis=None, edge_order=1)Same shape as the inputCentral differences inside; first- or second-order one-sided differences at the boundaries (edge_order)
pandas.Series.diffSeries.diff(periods=1)Same length as the SeriesLeading periods positions are filled with a missing value

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about NumPy diff: np.diff Syntax, Axis, n and prepend

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →