TExcelTAD
Home › NumPy › ufunc Differences

ufunc Differences

A discrete difference subtracts each element from the one after it. For [10, 15, 25] the differences are [15 − 10, 25 − 15] = [5, 10]. NumPy's np.diff() computes them, and the result is always one element shorter than the input.

python · try it yourself
import numpy as np

odometer = np.array([12_000, 12_045, 12_130, 12_130, 12_210])   # km at each day's start
print(np.diff(odometer))           # km driven each day
[45 85  0 80]

Differences answer "how much did it change?": daily distance from an odometer, daily new cases from a cumulative count, price movements from a price series.

Repeated differences with n

The n argument applies the difference several times. The second difference measures how the change itself changes, like acceleration from position:

python · try it yourself
import numpy as np

t = np.arange(6)
position = t ** 2                  # a falling ball, roughly: 0, 1, 4, 9, 16, 25
print(position)
print(np.diff(position))           # speed:        1 3 5 7 9
print(np.diff(position, n=2))      # acceleration: 2 2 2 2
[ 0  1  4  9 16 25]
[1 3 5 7 9]
[2 2 2 2]

For n=2, NumPy first computes [1, 3, 5, 7, 9], then the difference of that: [2, 2, 2, 2]. A constant second difference is the signature of a quadratic sequence.

Differences along an axis

On a 2-D array np.diff works along the last axis by default (within each row). Use axis=0 for differences between rows:

python · try it yourself
import numpy as np

# Cumulative app downloads, rows = apps, columns = months
downloads = np.array([[100, 180, 300, 390],
                      [ 50,  60,  65,  90]])
print(np.diff(downloads))          # new downloads per month for each app
print(np.diff(downloads, axis=0))  # gap between the apps each month
[[ 80 120  90]
 [ 10   5  25]]
[[ -50 -120 -235 -300]]

Undoing a cumulative sum

np.diff is the inverse of np.cumsum. With prepend (or append) you keep the array length, which lets you recover the original values exactly:

python · try it yourself
import numpy as np

daily = np.array([3, 5, 2, 8, 4])
total = np.cumsum(daily)
print(total)
print(np.diff(total, prepend=0))   # back to the daily values
[ 3  8 10 18 22]
[3 5 2 8 4]

Example: finding changes and trends

Differences are useful for detecting when something changes direction or jumps:

python · try it yourself
import numpy as np

price = np.array([101.0, 102.5, 101.8, 103.2, 107.9, 107.1, 106.4])
change = np.diff(price)
print("changes:", change.round(1))
print("up days:", np.sum(change > 0), " down days:", np.sum(change < 0))
print("largest jump on day", change.argmax() + 1, "by", change.max().round(1))
pct = (np.diff(price) / price[:-1] * 100).round(2)
print("percent change:", pct)
changes: [ 1.5 -0.7  1.4  4.7 -0.8 -0.7]
up days: 3  down days: 3
largest jump on day 4 by 4.7
percent change: [ 1.49 -0.68  1.38  4.55 -0.74 -0.65]

price[:-1] is every price except the last: the "previous day" for each change. Pairing np.diff(a) with a[:-1] is the standard way to get relative changes.

Test yourself

What is np.diff([1, 4, 9, 16])?

  1. [3 5 7]
  2. [1 4 9]
  3. [2 2]
  4. [4 9 16]

An array has 10 elements. How many does np.diff(a, n=2) have?

  1. 10
  2. 9
  3. 8
  4. 5

Which call restores x from c = np.cumsum(x)?

  1. np.diff(c)
  2. np.diff(c, prepend=0)
  3. np.cumprod(c)
  4. np.diff(c, n=2)