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

import numpy as np

arr = np.array([1, 3, 6, 10])
diff_arr = np.diff(arr)

print(diff_arr) # [2 3 4] -> 3-1=2, 6-3=3, 10-6=4

  • Computes: arr[i+1] - arr[i]

  • Result array length = original length - 1


✅ 2. Difference of Higher Order

  • Use n parameter to compute higher-order differences

arr = np.array([1, 3, 6, 10])
diff2 = np.diff(arr, n=2)

print(diff2) # [1 1] -> second-order differences

  • First-order difference: [2,3,4]

  • Second-order difference: [3-2,4-3] = [1,1]


✅ 3. Differences Along an Axis (2D Array)

arr2d = np.array([[1, 2, 4],
[5, 6, 8]])

# Difference along columns (axis=1)
diff_axis1 = np.diff(arr2d, axis=1)
print("Axis=1:\n", diff_axis1)
# [[1 2]
# [1 2]]

# Difference along rows (axis=0)
diff_axis0 = np.diff(arr2d, axis=0)
print("Axis=0:\n", diff_axis0)
# [[4 4 4]]

  • 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

position = np.array([0, 2, 6, 12])
velocity = np.diff(position) # Δx = x[i+1] - x[i]
print(velocity) # [2 4 6]

✅ 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

  1. Compute first and second-order differences of [2, 5, 9, 14, 20].

  2. Create a 2×3 array and compute differences along both axes.

  3. Compute the daily change of stock prices [100, 102, 105, 107, 110].

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *