Computing n discrete differences in Python
Computing n-th discrete differences in Python
To compute the n-th discrete difference, use the numpy.diff() method. The first difference along a given axis is given by out[i] = a[i + 1] – a[i], and higher differences are computed recursively using diff. The diff() method returns the n-th difference. The shape of the output is the same as a, except that the axis along the dimension n is smaller. The type of the output is the same as the difference between any two elements of a. In most cases, this is the same type as a. Of note is datetime64, which results in a timedelta64 output array.
The first argument is the input array, and the second argument is n, the number of times the value is to be differencing. If it is zero, the original input is returned. The third argument is the axis along which the difference is to be taken, which defaults to the last axis. The fourth argument is the value to be appended to the input array before performing the difference. Scalar values are expanded to arrays with length 1 along the axis and to the shape of the input array along all other axes.
Steps
First, import the required libraries −
import numpy as np
Use the array() method to create a NumPy array. We added int elements and NaN −
arr = np.array([10, 15, 30, 65, 80, 87, np.nan])
Displaying the array −
print("Our array...n", arr)
Checking the dimensions −
print("nOur array dimensions...n", arr.ndim)
Getting the data type −
print("nOur array object data type...n", arr.dtype)
To compute the nth discrete difference, use the numpy.diff() method. The first difference along a given axis is given by out[i] = a[i + 1] – a[i], and higher differences are recursively calculated using diff −
print("n discrete differences...n", np.diff(arr))
Example
import numpy as np
# Create a numpy array using the array() method
# We add int elements and NaNs
arr = np.array([10, 15, 30, 65, 80, 87, np.nan])
# Display the array
print("Our array...n", arr)
# Check the dimensions
print("n our array dimensions...n", arr.ndim)
# Get the data type
print("n the data type of our array object...n", arr.dtype)
# To compute the nth discrete difference, use the numpy.diff() method.
# The first difference along a given axis is given by out[i] = a[i + 1] - a[i]. Higher differences are computed recursively using diff.
print("n discrete differences..n",np.diff(arr))
Output
Our array...
[10. 15. 30. 65. 80. 87. nan]
Our array dimensions...
1
The data type of our array object...
float64
Discrete differences...
[5. 15. 35. 15. 7. nan]