numpy.diff() in Python
numpy.diff() calculate the n-th discrete difference along the specified axis. It is commonly used to find differences between consecutive elements in a NumPy array, such as in time series or signal data. Example:
import numpy as np
a = np.array([1, 2, 4, 7, 0])
res = np.diff(a)
print(res)
Output
[ 1 2 3 -7]
Explanation: np.diff() returns the difference between each pair of consecutive elements 2-1, 4-2, 7-4, 0-7-> 1,2,3,-7.
Syntax
numpy.diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>)
Parameters:
Parameter | Description |
---|---|
a | Input array |
n | Number of times values are differenced. Default is 1 |
axis | Axis along which the difference is taken. Default is the last axis |
prepend | Values to prepend to a before performing the difference |
append | Values to append to a before performing the difference |
Returns: A new array with the same shape as a except along the specified axis, where the dimension is reduced by n (unless prepend or append is used).
Examples
Example 1: In this example, we use the n=2 parameter to calculate the second discrete difference of the array.
import numpy as np
a = np.array([1, 2, 4, 7, 0])
res = np.diff(a, n=2)
print(res)
Output
[ 1 1 -10]
Explanation: We compute the second-order difference by applying np.diff() twice first, np.diff(a) gives [1, 2, 3, -7] (first differences), then applying np.diff() again gives [1, 1, -10], the second-order differences.
Example 2: In this example, we use the axis=1 parameter to compute the difference between elements along each row of a 2D array.
import numpy as np
a = np.array([[1, 2, 4], [3, 5, 9]])
res = np.diff(a, axis=1)
print(res)
Output
[[1 2] [2 4]]
Explanation: We compute the difference along each row using axis=1. For the first row 2−1 = 1, 4−2 = 2 -> [1, 2] and for the second row: 5−3 = 2, 9−5 = 4 → [2, 4]. The function operates independently on each row.
Example 3: In this example, we prepend a value (0) before the array to compute differences without reducing the output length.
import numpy as np
a = np.array([5, 10, 15])
res = np.diff(a, prepend=0)
print(res)
Output
[5 5 5]
Explanation: By default, np.diff() reduces the array length by one. To retain the original size, we use prepend=0, which adds a 0 at the start: [0, 5, 10, 15]. The differences then are: 5−0 = 5, 10−5 = 5, 15−10 = 5 -> [5, 5, 5].
Example 4: In this example, we append a value (0) at the end of the array to compute differences including a trailing comparison.
import numpy as np
a = np.array([1, 2, 3])
res = np.diff(a, append=0)
print(res)
Output
[ 1 1 -3]
Explanation: Here, we use append=0 to add a value at the end, making the array [1, 2, 3, 0]. Now the differences are: 2−1 = 1, 3−2 = 1 and 0−3 = -3 -> [1, 1, -3].