NumPy diff()
The numpy.diff() function calculates the n-th discrete difference of an array along a specified axis.
It is commonly used to compute differences between consecutive elements.
The nth discrete difference refers to the process of computing the difference between elements of a sequence multiple times iteratively.
Given a sequence of numbers, the first discrete difference is simply the difference between consecutive elements. If we continue applying the difference operation repeatedly, we obtain the nth discrete difference.
Syntax
numpy.diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>)
Parameters
| Parameter | Type | Description |
|---|---|---|
a | array_like | Input array for which differences are computed. |
n | int, optional | Number of times values are differenced. Default is 1. |
axis | int, optional | Axis along which the difference is calculated. Default is the last axis (-1). |
prepend | array_like, optional | Values to prepend before computing differences. |
append | array_like, optional | Values to append before computing differences. |
Return Value
Returns an array of differences with the same shape as a, except along the specified axis where its size is reduced by n.
The data type of the output depends on the difference calculation.
Examples
1. Calculating First-Order Differences
Computing the first-order discrete difference of a simple array.
import numpy as np
# Define an input array
arr = np.array([10, 15, 25, 40])
# Compute first-order differences
result = np.diff(arr)
# Print the result
print("First-order differences:", result)
Output:
First-order differences: [ 5 10 15]
