How to use the np.multiply() function for a 2D array in Python
Overview
The python library NumPy has a method called multiply() which can be used to multiply two input arrays.
The numpy.multiply() method
The numpy.multiply() method returns the product of the two input arrays, element-wise.
Note: A two-dimensional (2D) array can be created using a list of lists in Python.
Syntax
numpy.multiply(arr1, arr2, dtype=None, out=None)
Parameters
arr1: This represents the input data.arr2: This represents the input data.dtype: This is an optional parameter. It represents the return type of the array.out: This is an optional parameter. It represents the alternative output array in which the result is to be placed.
Return value
The numpy.prod() method returns the product of the arr1 and arr2 arrays element by element.
Note: If the
outparameter is specified, it returns an array reference toout.
Example
The following code shows how to multiply two-dimensional (2D) arrays using the numpy.multipy() method.
# import numpyimport numpy as np# create a two 2D arraysarr1 = np.array([[2,6,5],[3,4,8]])arr2 = np.array([[1,7,2],[10,9,4]])# multiply the 2D arrays# and store the result in arr_mularr_mul = np.multiply(arr1, arr2)print(arr_mul)
Explanation
- Line 2: We import the
numpylibrary. - Lines 4–5: We create two 2D arrays,
arr1andarr2. - Line 9: We use
np.multiply()to multiple the arraysarr1andarr2. - Line 11: We display the result.