w3resource

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

NumPy Mathematics: Exercise-29 with Solution

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:

Previous: Write a NumPy program to calculate cumulative product of the elements along a given axis, sum over rows for each of the 3 columns and product over columns for each of the 2 rows of a given 3x3 array.

Next: Write a NumPy program to calculate the difference between neighboring elements, element-wise, and prepend [0, 0] and append[200] to a given array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-math-exercise-29.php