w3resource

NumPy: Calculate the difference between neighboring elements, element-wise, and prepend [0, 0] and append [200] to a given array

NumPy Mathematics: Exercise-30 with Solution

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

Sample Solution:-

Python Code:

import numpy as np
x = np.array([1, 3, 5, 7, 0])
print("Original array: ")
print(x)
r1 = np.ediff1d(x, to_begin=[0, 0], to_end=[200])
r2 = np.insert(np.append(np.diff(x), 200), 0, [0, 0])
assert np.array_equiv(r1, r2)
print("Difference between neighboring elements, element-wise, and prepend [0, 0] and append[200] to the said array:")
print(r2)

Sample Output:

Original array: 
[1 3 5 7 0]
Difference between neighboring elements, element-wise, and prepend [0, 0] and append[200] to the said array:
[  0   0   2   2   2  -7 200]

Python Code Editor:

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

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

Next: Write a NumPy program to compute ex, element-wise of a given array

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Getting rid of unwanted characters:

You can get rid of whitespaces or any specific character using strip methods in Python. You can use either plain strip for both sides, lstrip for the left side and rstrip for the right side only.

str="+++Welcome python+++"
str.strip()

print(str)

Output:

+++Welcome python+++