How to use the numpy.trapz() method for 2D array in Python
The numpy.trapz() method
The numpy.trapz() method is used to compute integration along a specified axis using the composite trapezoidal rule.
Note: A two-dimensional (2D) array can be created in Python using a list of lists.
Syntax
numpy.trapz(y, x=None, dx=1.0, axis=- 1)
Parameters
y: This denotes the array of inputs to be integrated.x: This is array-like, but not required. It reflects theyvalues’ sample points. The sample points are considered to be evenly spread at a distance ofdxifxis set to None. The default is None.dx: This is an optional scalar variable. Whenxis None, it reflects the distance between samples. The default value is1.axis: This is theintvalue and optional. It represents the integration axis.
Return value
The numpy.trapz() method returns a definite integral estimated by the trapezoidal rule. It can be a float or ndarray.
Example
The following code shows how to use the numpy.trapz() method for two-dimensional (2D) arrays.
# import numpyimport numpy as np# create listx1 = [7,3,4,8]x2 = [2,6,9,5]# convert the lists to 2D array using np.arrayy = np.array([x1,x2])# compute the integration along a specified axis# and store the result in resultresult = np.trapz(y, dx=2)print(result)
Explanation
- Line 2: We import the
numpylibrary. - Lines 4–5: We create two separate lists,
x1andx2. - Line 7: We utilize the
np.array()method to convert the lists into a 2D array. We save in a new variable calledy. - Line 11: We use
np.trapz()to compute the integration along a specified axis. The result is stored in a new variable calledresult. - Line 13: We display the result.