What is the numpy.diff() function in NumPy?

Overview

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]

Syntax

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

Parameter values

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.

Return value

The numpy.diff() function returns an array containing the nth differences of the input array elements.

Code example

import numpy as np
# creating an array
a = np.array([1, 2, 3, 4, 5])
# Implementing the numpy.diff() function
myarray = np.diff(a, axis=0)
print(a)
print(myarray)

Code explanation

  • Line 1: We import the numpy module.
  • Line 4: We create an array, a, using the array() method.
  • Line 7: We implement the numpy.diff() function on the array. The result is assigned to a variable, myarray.
  • Line 9: We print the input array a.
  • Line 10: We print the variable 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].

Free Resources