w3resource

NumPy: Calculate the difference between neighboring elements, element-wise of a given array


29. Element-wise Difference of Neighboring Elements

Write a NumPy program to calculate the difference between neighboring elements, element-wise of a given array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array
x = np.array([1, 3, 5, 7, 0])

# Displaying the original array
print("Original array: ")
print(x)

# Calculating the difference between neighboring elements, element-wise
print("Difference between neighboring elements, element-wise of the said array.")
print(np.diff(x)) 

Sample Output:

Original array: 
[1 3 5 7 0]
Difference between neighboring elements, element-wise of the said array.
[ 2  2  2 -7]

Explanation:

x = np.array([1, 3, 5, 7, 0]): Create an input array x with 5 elements.

np.diff(x): This line calculates the difference between consecutive elements of x.

The output will be a new array with 4 elements, where each element is equal to the difference between the i-th and (i-1)-th element of x. In this case, the output will be [2, 2, 2, -7], as follows:

  • The difference between the 2nd and 1st elements of x is 3 - 1 = 2.
  • The difference between the 3rd and 2nd elements of x is 5 - 3 = 2.
  • The difference between the 4th and 3rd elements of x is 7 - 5 = 2.
  • The difference between the 5th and 4th elements of x is 0 - 7 = -7.

For more Practice: Solve these Related Problems:

  • Implement a function that uses np.diff to compute the difference between neighboring elements in a 1D array.
  • Test the function on both 1D and 2D arrays and verify that differences are computed along the correct axis.
  • Create a solution that reconstructs the original array from the differences using np.cumsum.
  • Compare the output of np.diff with manual difference calculations for validation on test inputs.

Go to:


PREV : Cumulative Product and Row/Column Products
NEXT : Extended Difference with Prepend and Append

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.