NumPy Tutorial NumPy Statistics NumPy References

NumPy - diff() function



The NumPy diff() function is used to calculate the n-th discrete difference along the given axis. For example, the first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by this function recursively.

Syntax

numpy.diff(a, n=1, axis=-1, 
           prepend=<no value>, 
           append=<no value>)

Parameters

a Required. Specify the input array (array_like).
n Optional. Specify the number of times values are differenced. If zero, the input is returned as it is.
axis Optional. Specify the axis along which the difference is taken, default is the last axis.
prepend, append Optional. Specify the values to prepend or append to a along axis prior to performing the difference. Scalar values are expanded to arrays with length 1 in the direction of axis and the shape of the input array in along all other axes. Otherwise the dimension and shape must match a except along axis.

Return Value

Returns an array with n-th discrete difference along the given axis of a. The shape of the output is the same as a except along axis where the dimension is smaller by n.

Example:

In the example below, diff() function is used to get the first difference of a 1-D array.

import numpy as np

Arr = np.array([10, 11, 13, 16, 20, 25])

#first difference array
diff1 = np.diff(Arr, 1)
#second difference array
diff11 = np.diff(diff1, 1)

#second difference array 
#in one step
diff2 = np.diff(Arr, 2)

#displaying the result
print("Array :", Arr)
print("diff1 :", diff1)
print("diff11 :", diff11)
print("diff2 :", diff2)

The output of the above code will be:

Array : [10 11 13 16 20 25]
diff1 : [1 2 3 4 5]
diff11 : [1 1 1 1]
diff2 : [1 1 1 1]

Example:

The diff() function can be used along a given axis as shown in the example below.

import numpy as np

Arr = np.array([[10, 11, 13], 
                [16, 20, 25],
                [31, 38, 46]])

#first difference along axis=0
diff0 = np.diff(Arr, 1, axis=0)
#second difference along axis=1
diff1 = np.diff(Arr, 1, axis=1)

#displaying the result
print("Array :")
print(Arr)
print("\ndiff0 :")
print(diff0)
print("\ndiff1 :")
print(diff1)

The output of the above code will be:

Array :
[[10 11 13]
 [16 20 25]
 [31 38 46]]

diff0 :
[[ 6  9 12]
 [15 18 21]]

diff1 :
[[1 2]
 [4 5]
 [7 8]]

❮ NumPy - Functions