Element-wise multiplication in NumPy is straightforward. You can perform it using either the *
operator or the numpy.multiply()
function. Here’s the syntax for both approaches:
Using the *
operator:
result = array1 * array2
Using the numpy.multiply()
function:
result = np.multiply(array1, array2)
In both cases:
array1
andarray2
are NumPy arrays that you want to multiply element-wise.result
will contain the result of the element-wise multiplication, where each element inresult
will be the product of the corresponding elements inarray1
andarray2
.
You can replace array1
and array2
with your own NumPy arrays as needed, and the element-wise multiplication will work the same way.
Element-wise multiplication NumPy example
Here’s an example of element-wise multiplication in NumPy:
import numpy as np
# Create two NumPy arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# using the * operator
result = array1 * array2
print("Element-wise multiplication using * operator:")
print(result)
# using numpy.multiply()
result2 = np.multiply(array1, array2)
print("\nElement-wise multiplication using np.multiply():")
print(result2)
Output:
The *
operator and the numpy.multiply()
function performs element-wise operations, which means they multiply each element in array1
with the corresponding element in array2
.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.