Skip to content
Related Articles

Related Articles

Improve Article

How to calculate the difference between neighboring elements in an array using NumPy

  • Last Updated : 02 Sep, 2020

Let’s see how to calculate the difference between neighboring elements in an array using NumPy library.

So, We can find out the difference between neighboring elements using numpy.diff() function of NumPy library.

Syntax: numpy.diff(arr, n, axis)

Now, let’s see an example:

Example 1:



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]

Example 2:

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]]

Example 3:

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]]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :