NumPy multiply()
Summary: in this tutorial, you’ll learn how to use the numpy multiply()
function or the * operator to return the product of two equal-sized arrays, element-wise.
Introduction to the Numpy subtract function
The *
operator or multiply()
function returns the product of two equal-sized arrays by performing element-wise multiplication.
Let’s take some examples of using the *
operator and multiply()
function.
Using NumPy multiply() function and * operator to return the product of two 1D arrays
The following example uses the *
operator to get the products of two 1-D arrays:
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])
c = a*b
print(c)
Output:
[3 8]
How it works.
First, create two 1D arrays with two numbers in each:
a = np.array([1, 2])
b = np.array([3, 4])
Second, get the product of two arrays a and b by using the *
operator:
c = a * b
The *
operator returns the product of each element in array a with the corresponding element in array b:
[1*3, 2*4] = [3,8]
Similarly, you can use the multiply()
function to get the product between two 1D arrays as follows:
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])
c = np.multiply(a, b)
print(c)
Output:
[3 8]
Using NumPy multiply() function and * operator to get the product of two 2D arrays
The following example uses the * operator to get the products of two 2D arrays:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = a*b
print(c)
Output:
[[ 5 12]
[21 32]]
In this example, the *
operator performs element-wise multiplication:
[[ 1*5 2*6]
[3*7 4*8]]
Likewise, you can use the multiply()
function to find the products of two 2D arrays:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = np.multiply(a, b)
print(c)
Output:
[[ 5 12]
[21 32]]
Summary
- Use the
*
operator ormultiply()
function to find the product of two equal-sized arrays.