How to use the np.mod() function for a 2D array in Python
Overview
In Python’s NumPy library, the mod() method returns the remainder of a division.
The numpy.mod() method returns the remainder after dividing two input arrays. This is done element-wise (element by element).
Note: In Python, a list of lists can be used to create a two-dimensional (2D) array.
Syntax
numpy.mod(x1, x2, dtype=None, out=None)
Parameters
x1: This is an array that represents the data input. This is the dividend.x2: This is an array that represents the data input. This is the divisor.dtype: This is an optional parameter. It represents the array’s return type.out: This is an optional parameter. It denotes the alternate output array where the result will be stored.
Note: If the shapes of
x1andx2differ, they must be able to be broadcasted to a common shape for output representation.
Return value
The numpy.mod() method returns an array that contains the remainder from the (x1/x2) arrays.
Note: In Python, the
modfunction is equivalent to the modulus operator,x1 % x2.
Code
The following code shows how to use the numpy.mod() method for two-dimensional (2D) arrays:
# import numpyimport numpy as np# create a two 2D arraysx1 = np.array([[2,6,5],[3,4,8]])x2 = np.array([[1,7,2],[10,9,4]])# divide the 2D arrays# and store the remainder in resultresult = np.mod(x1, x2)print(result)
Explanation
- Line 2: We import the
numpylibrary. - Line 4-5: We create two 2D arrays called
x1andx2. - Line 9: We use the
np.mod()method. This returns an array containing the remainder of dividing arrayx1by arrayx2. The result is stored in a new array calledresult. - Line 11: We display the result.