Calculate nth discrete difference along a given axis in Python

Computing the nth discrete difference along a given axis in Python

To compute the nth discrete difference, use the numpy.diff() method. The first difference is given by out[i] = a[i+1] – a[i] along a given axis, and higher-order differences are computed recursively using diff(). The diff() method returns the nth difference. The output has the same shape as a, except that the number of dimensions along the axis is smaller than n. The type of the output is the same as the difference between any two elements in a. In most cases, this is the same type as a. Note that datetime64 produces a timedelta64 output array.

The first argument is the input array. The second argument is n, the number of times the values are to be differencing. If it is zero, the input is returned unchanged. The third argument is the axis along which the differences are to be performed; the default is the last axis. The fourth argument is the value to be added or appended to the input array before performing the differences. Scalar values are expanded to arrays of length 1 in the direction of the axis and to the shape of the input array in all other axes.

Steps

First, import the required libraries –

import numpy as np

Use the array() method to create a NumPy array. We have added an int element with a nan.

arr = np.array([[10, 15, 30, 65], [80, 87, 100, np.nan]])

Displaying the array

print("Our array...n",arr)

Checking the array’s dimensions

print("nThe dimension of our array...n",arr.ndim)

Getting 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 is given by out[i] = a[i+1] – a[i] along a given axis. Higher-order differences are computed recursively using diff() –

print("n discrete differences...n", np.diff(arr, axis = 1))

Example

import numpy as np

# Create a numpy array using the array() method
# We have added an int element with a nan
arr = np.array([[10, 15, 30, 65], [80, 87, 100, np.nan]])

# Display the array
print("Our array...n",arr)

# Check the array's dimensions
print("nThe dimensions of our array...n",arr.ndim)

# Get the data type
print("The data type of our array object...n",arr.dtype)

# To compute the nth discrete difference, use the numpy.diff() method.
# The first difference is given by out[i] = a[i+1] - a[i] along a given axis. Higher-order differences are computed recursively using diff().
print("n discrete difference..n", np.diff(arr, axis = 1))

Output

Our array...
[[ 10. 15. 30. 65.]
[ 80. 87. 100. nan]]

The dimension of our array...
2

The data type of our array object...
float64

The discrete difference..
[[ 5. 15. 35.]
[ 7. 13. nan]]

Leave a Reply

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