NumPy: How to Calculate the Difference Between Neighboring Elements in Array
To calculate the difference between neighboring elements in an array using the NumPy library we use numpy.diff() method of NumPy library.
It is used to find the n-th discrete difference along the given axis.
The first output is given by:
difference[i] = a[i+1] - a[i]
Example:
Python NumPy program to calculate differences between neighboring elements in a 2d NumPy array
Python3
# import library import numpy as np # create a numpy 2d-array arr = np.array([[ 10 , 12 , 14 ], [ 25 , 35 , 45 ], [ 12 , 18 , 20 ]]) # finding the difference between # neighboring elements along column result = np.diff(arr, axis = 0 ) print (result) |
Output:
[[ 15 23 31]
[-13 -17 -25]]
Syntax
Syntax: numpy.diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>)
Parameters
- a: Input array
- n: The number of times values are differenced.
- axis: The axis along which the difference is taken, default is the last axis.
- prepend, append: Values to prepend or append to a along axis prior to performing the difference.
Returns: returns the n-th differences
Let’s check some examples of how to calculate the difference between neighboring elements in an array using NumPy to get a better understanding:
More Examples
Let’s look at examples for 1D and 2D arrays:
Calculating Differences Between Consecutive Elements in a 1D Numpy Array
Python3
# import library import numpy as np # create a numpy 1d-array arr = np.array([ 1 , 12 , 3 , 14 , 5 , 16 , 7 , 18 , 9 , 110 ]) # finding the difference between # neighboring elements result = np.diff(arr) print (result) |
Output:
[ 11 -9 11 -9 11 -9 11 -9 101]
Calculating Differences Between Neighboring Elements Along Rows in a 2D NumPy Array
Python3
# import library import numpy as np # create a numpy 2d-array arr = np.array([[ 10 , 12 , 14 ], [ 25 , 35 , 45 ], [ 12 , 18 , 20 ]]) # finding the difference between # neighboring elements along row result = np.diff(arr, axis = 1 ) print (result) |
Output:
[[ 2 2]
[10 10]
[ 6 2]]