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)
Code language: Python (python)
Output:
[3 8]
Code language: Python (python)
How it works.
First, create two 1D arrays with two numbers in each:
a = np.array([1, 2])
b = np.array([3, 4])
Code language: Python (python)
Second, get the product of two arrays a and b by using the *
operator:
c = a * b
Code language: Python (python)
The *
operator returns the product of each element in array a with the corresponding element in array b:
[1*3, 2*4] = [3,8]
Code language: Python (python)
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)
Code language: Python (python)
Output:
[3 8]
Code language: Python (python)
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)
Code language: Python (python)
Output:
[[ 5 12]
[21 32]]
Code language: Python (python)
In this example, the *
operator performs element-wise multiplication:
[[ 1*5 2*6]
[3*7 4*8]]
Code language: Python (python)
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)
Code language: Python (python)
Output:
[[ 5 12]
[21 32]]
Code language: Python (python)
Summary
- Use the
*
operator ormultiply()
function to find the product of two equal-sized arrays.