How to use the np.diff() method for a 2D array in Python
Overview
The numpy.diff() method is used to find the nth order of discrete difference along a specified axis.
Note: In Python, a list of lists can be used to create a two-dimensional (2D) array.
Syntax
The syntax for the numpy.diff() method is as follows:
numpy.diff(a, n=1, axis=-1)
Parameters
-
a: This represents the input data. -
n: This is an optional parameter. It denotes the number of times the difference value is calculated. -
axis: This is an optional parameter. It denotes the axis over which the difference is calculated.
Return value
The numpy.diff() method returns the nth order of discrete difference along a given axis.
Example
The following code shows how to use the numpy.diff() method for two-dimensional (2D) arrays.
# import numpyimport numpy as np# create listx1 = [3,4,8]x2 = [2,6,5]# convert the lists to 2D array using np.arraya = np.array([x1,x2])# compute the n-th discrete order difference# and store the result in resultresult = np.diff(a, axis=0)print(result)
Explanation
The following is the explanation for the code above:
- Line 2: We import the
numpylibrary. - Lines 4 and 5: We create two lists called
x1andx2. - Line 7: We use the
np.array()method to convert the lists to a 2D array. - Line 11: We use
np.diff()to compute the nth discrete difference alongaxis=0. The result is stored in a new variable calledresult. - Line 13: We display the result.