The numpy.diff()
function in NumPy is used to compute the nth difference along the given axis of an input array.
For example, for an input array:
a = [n1, n2, n3, n4, n5]
numpy.diff(x) = [n2-n1, n3-n2, n4-n3, n5-n4]
numpy.diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>)
The numpy.diff()
function takes the following parameter values:
a
: This is the input array and is a required parameter.n
: This is the number of times the difference value is taken and is an optional parameter.axis
: This is the given axis over which the difference is taken and is an optional parameter.preprend
, append
: These are the values to prepend or append to the input array, a
, along the axis before performing the difference. This is an optional parameter.The numpy.diff()
function returns an array containing the nth differences of the input array elements.
import numpy as np# creating an arraya = np.array([1, 2, 3, 4, 5])# Implementing the numpy.diff() functionmyarray = np.diff(a, axis=0)print(a)print(myarray)
numpy
module.a
, using the array()
method.numpy.diff()
function on the array. The result is assigned to a variable, myarray
.a
.myarray
.Note: From the output of the code, the working is given as
numpy.diff(a) = [2-1, 3-2, 4-3, 5-4] = [1, 1, 1, 1]
.