The numpy module of Python provides a function called numpy.diff for calculating the nth discrete difference along the given axis. If 'x' is the input array, then the first difference is given by out[i]=x[i+1]-a[i]. We can calculate the higher difference by using diff recursively. The numpy module of Python provides a function called numpy.diff for calculating the nth discrete difference along the given axis. If 'x' is the input array, then the first difference is given by out[i]=x[i+1]-a[i]. We can calculate the higher difference by using diff recursively.
numpy.diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>)
x: array_like
This parameter defines the source array whose elements nth discrete deference are those which we want to calculate.
n: int(optional)
This parameter defines the number of times the values are differenced. If it is 0, then the source array is returned as it is.
append, prepend: array_like(optional)
This parameter defines a ndarray, which defines the values going to append or prepend to 'x', along the axis before computing differences.
This function returns a ndarray containing nth differences having the same shape as 'x,' and the dimension is smaller from n. The type of difference between any two elements of 'x' is the type of the output.
import numpy as np arr = np.array([0, 1, 2], dtype=np.uint8) arr b=np.diff(arr) b arr[2,...] - arr[1,...] - arr[0,...]
Output:
In the above code
In the output, it shows the discrete differences of elements.
import numpy as np x = np.array([11, 21, 41, 71, 1, 12, 33, 2]) y = np.diff(x) x y
Output:
import numpy as np x = np.array([[11, 21, 41], [71, 1, 12], [33, 2, 13]]) y = np.diff(x, axis=0) y z = np.diff(x, axis=1) z
Output:
import numpy as np x = np.arange('1997-10-01', '1997-12-16', dtype=np.datetime64) y = np.diff(x) y
Output:
In the above code
In the output, it shows the discrete differences between dates.