diff¶
- diff(x: array, /, *, axis: int = -1, n: int = 1, prepend: array | None = None, append: array | None = None) array¶
Calculates the n-th discrete forward difference along a specified axis.
- Parameters:
x (array) – input array. Should have a numeric data type.
axis (int) – axis along which to compute differences. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute differences by counting backward from the last dimension (where-1refers to the last dimension). If provided an invalidaxis, the function must raise an exception. Default:-1.n (int) – number of times to recursively compute differences. Default:
1.prepend (Optional[array]) – values to prepend to a specified axis prior to computing differences. Must have the same shape as
x, except for the axis specified byaxiswhich may have any size. Should have the same data type asx. Default:None.append (Optional[array]) – values to append to a specified axis prior to computing differences. Must have the same shape as
x, except for the axis specified byaxiswhich may have any size. Should have the same data type asx. Default:None.
- Returns:
out (array) – an array containing the n-th differences. Should have the same data type as
x. Must have the same shape asx, except for the axis specified byaxiswhich must have a size determined as follows:Let
Mbe the number of elements along an axis specified byaxis.Let
N1be the number of prepended values along an axis specified byaxis.Let
N2be the number of appended values along an axis specified byaxis.The final size of the axis specified by
axismust beM + N1 + N2 - n.
Notes
The first-order differences are given by
out[i] = x[i+1] - x[i]along a specified axis. Higher-order differences must be calculated recursively (e.g., by callingdiff(out, axis=axis, n=n-1)).If a conforming implementation chooses to support
prependandappendarrays which have a different data type thanx, behavior is unspecified and thus implementation-defined. Implementations may choose to type promote (Type Promotion Rules), castprependand/orappendto the same data type asx, or raise an exception.
New in version 2024.12.