NumPy Differences
➖ NumPy Differences (np.diff)
The NumPy diff() function calculates the difference between consecutive elements in an array. It is useful for numerical differentiation, trend analysis, and signal processing.
✅ 1. Basic np.diff() on 1D Array
-
Computes:
arr[i+1] - arr[i] -
Result array length =
original length - 1
✅ 2. Difference of Higher Order
-
Use
nparameter to compute higher-order differences
-
First-order difference:
[2,3,4] -
Second-order difference:
[3-2,4-3] = [1,1]
✅ 3. Differences Along an Axis (2D Array)
-
axis=0→ differences down rows -
axis=1→ differences across columns
✅ 4. Applications
-
Numerical derivatives in scientific computing
-
Velocity / acceleration from position arrays
-
Change detection in signals or stock prices
✅ 5. Notes & Tips
-
Output length =
original length - n -
Use
np.gradient()if you need centered differences for derivative approximation -
Works with 1D, 2D, or ND arrays
🎯 Practice Exercises
-
Compute first and second-order differences of
[2, 5, 9, 14, 20]. -
Create a 2×3 array and compute differences along both axes.
-
Compute the daily change of stock prices
[100, 102, 105, 107, 110].
