w3resource

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


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.

Python-Numpy Code Editor: