Javatpoint Logo
Javatpoint Logo

numpy.diff() in Python

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.

Syntax

Parameters

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.

Returns:

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.

Example 1:

Output:

array([0, 1, 2], dtype=uint8)
array([1, 1], dtype=uint8)
1

In the above code

  • We have imported numpy with alias name np.
  • We have created an array 'arr' using np.array() function with the dtype 'uint8'.
  • We have declared the variable 'b' and assigned the returned value of the np.diff() function.
  • We have passed the array 'arr' in the function.
  • Lastly, we tried to print the value of 'b' and the difference between elements.

In the output, it shows the discrete differences of elements.

Example 2:

Output:

array([11, 21, 41, 71,  1, 12, 33,  2])
array([ 10,  20,  30, -70,  11,  21, -31])

Example 3:

Output:

array([[ 60, -20, -29],
       	[-38,   1,   1]])
array([[ 10,  20],
       	[-70,  11],
       	[-31,  11]])

Example 4:

Output:

array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       	1, 1, 1, 1, 1, 1, 1, 1, 1], dtype='timedelta64[D]')

In the above code

  • We have imported numpy with alias name np.
  • We have created an array of dates 'x' using np.arange() function with the dtype 'datetime64'.
  • We have declared the variable 'y' and assigned the returned value of the np.diff() function.
  • We have passed the array 'x' in the function.
  • Lastly, we tried to print the value of 'y'.

In the output, it shows the discrete differences between dates.


Next TopicNumpy.empty()




Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA