NumPy diff()
NumPy diff() function is used to find differences between consecutive numbers of elements in an array. The differences can be taken of first order or higher, that is, it can be the difference between consecutive elements only or it could be in between two elements.
Syntax
The syntax for NumPy diff() function is:
numpy.diff(a, n=1, axis=-1)
Here,
- a: Input array
- n: Order of differences. Default is 1 i.e. first order
- axis: Axis along which differences are computed. Default is -1 i.e. along the last axis
Example
import numpy as np
arr = np.array([7, 5, 3, 1, 0])
print("Original Array:\n", arr)
first_order_diff = np.diff(arr)
print("First Order Difference:\n", first_order_diff)
second_order_diff = np.diff(arr, 2)
print("Second Order Difference:\n", second_order_diff)
Output
Original Array:
[7 5 3 1 0]
First Order Difference:
[-2 -2 -2 -1]
Second Order Difference:
[ 0 0 1]
In the above example, we first created an input array "arr" and applied NumPy diff() function to find its first and second order differences.
Explanation
NumPy diff() function is used to find the differences between the consecutive numbers of elements in an array.
The optional parameter "n" refers to the order of the differences taken. If not specified, it is considered as 1 which means first-order differences.
The optional parameter "axis" specifies the axis along which differences are computed. The default is -1 which means that the differences are computed along the last axis.
Use
NumPy diff() function is widely used in data analysis and signal processing to find the first order or the second-order differences in a 1-D array.
NumPy diff() function is also used in cryptography to subtract corresponding characters in two strings.
Important Points
- The input array to NumPy diff() function should be 1-Dimensional
- By default, NumPy diff() function computes the first-order differences. For higher order differences, we need to specify the order in the function.
- The output array of NumPy diff() function will always be one element shorter than the input array.
Summary
NumPy diff() function is used to find the differences between the consecutive numbers of elements in an array. It is widely used in data analysis, signal processing, and cryptography. By default, it computes the first-order differences, but we can specify higher order differences as an optional parameter “n”.