Understanding Discrete Difference in NumPy with diff()
In data analysis and numerical computing, it's often useful to analyze how values change across a sequence. This is where discrete difference comes in.
What is Discrete Difference?
The discrete difference refers to the difference between consecutive elements in an array. In simple words, it means subtracting each element from the next one in the array.
[1, 2, 3, 4]
The difference between each successive pair:
2 - 1 = 1
3 - 2 = 1
4 - 3 = 1
So, the discrete difference becomes:
[1, 1, 1]
How to Compute Discrete Difference in NumPy?
You can easily compute this using NumPy’s diff() function.
Program:
import numpy as np
arr = np.array([10, 15, 25, 5])
newarr = np.diff(arr)
Output:
[ 5 10 -20]
Explanation:
Here’s what happens:
15 - 10 = 5
25 - 15 = 10
5 - 25 = -20
Thus, the result is [5, 10, -20].
Performing Multiple Differences with n Parameter
Want to repeat the difference operation multiple times? Just use the n parameter in np.diff().
Program:
import numpy as np
newarr = np.diff(arr, n=2)
print(newarr)
Output:
[ 5 -30]