Calculate the n-th discrete difference for unsigned integer arrays in Python

PythonNumpyServer Side ProgrammingProgramming

To calculate the n-th discrete difference, use the numpy.diff() method. The first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by using diff recursively. The 1st parameter is the input array. The 2nd parameter is n, i.e. the number of times values are differenced. If zero, the input is returned as-is. The 3rd parameter is the axis along which the difference is taken, default is the last axis.

The 4th parameter is the values to prepend or append to the input array along axis prior to performing the difference. Scalar values are expanded to arrays with length 1 in the direction of axis and the shape of the input array in along all other axes. Otherwise the dimension and shape must match a except along axis.

Steps

At first, import the required library −

import numpy as np

Creating a numpy array using the array() method. We have added elements of unsigned type. For unsigned integer arrays, the results will also be unsigned −

arr = np.array([1,0], dtype=np.uint8)

Display the array −

print("Our Array...
",arr)

Check the Dimensions −

print("
Dimensions of our Array...
",arr.ndim)

Get the Datatype −

print("
Datatype of our Array object...
",arr.dtype)

To calculate the n-th discrete difference, use the numpy.diff() method. The first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by using diff recursively −

print("
Discrete difference..
",np.diff(arr))

Example

import numpy as np

# Creating a numpy array using the array() method
# We have added elements of unsigned type
# For unsigned integer arrays, the results will also be unsigned.
arr = np.array([1,0], dtype=np.uint8)

# Display the array
print("Our Array...
",arr) # Check the Dimensions print("
Dimensions of our Array...
",arr.ndim) # Get the Datatype print("
Datatype of our Array object...
",arr.dtype) # To calculate the n-th discrete difference, use the numpy.diff() method # The first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by using diff recursively. print("
Discrete difference..
",np.diff(arr))

Output

Our Array...
[1 0]

Dimensions of our Array...
1

Datatype of our Array object...
uint8

Discrete difference..
[255]
raja
Updated on 25-Feb-2022 04:37:58

Advertisements