📜  Python| numpy numpy.ndarray.__mul__()(1)

📅  最后修改于: 2023-12-03 15:19:14.518000             🧑  作者: Mango

Python | numpy numpy.ndarray.__mul__()

The numpy.ndarray.\_\_mul\_\_() function in Python is used to perform element-wise multiplication of two arrays. It multiplies corresponding elements of two arrays and returns a new array with the same shape as the input arrays.

Syntax:
numpy.ndarray.__mul__(self, value, /)
Parameters:
  • self: Required, represents the input array.
  • value: Required, represents the value or array to multiply element-wise with the input array.
Returns:

The numpy.ndarray.\_\_mul\_\_() function returns a new array containing the multiplication of corresponding elements of the input arrays.

Example:
import numpy as np

# Creating input arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Performing element-wise multiplication
result = arr1.__mul__(arr2)

print(result)

Output:

array([ 4, 10, 18])

In the above example, two arrays arr1 and arr2 are created with values [1, 2, 3] and [4, 5, 6] respectively. The numpy.ndarray.\_\_mul\_\_() function is used to perform element-wise multiplication of these arrays, resulting in a new array [4, 10, 18].

Important Points:
  • The numpy.ndarray.\_\_mul\_\_() function is equivalent to using the * operator between arrays in numpy.
  • The shape of the input arrays should be the same, otherwise, the operation will result in an error.
  • Broadcasting rules apply for operations involving scalars and arrays of different shapes.

Please note that although the numpy.ndarray.\_\_mul\_\_() function is a valid method, it is generally recommended to use the * operator for element-wise multiplication in numpy, as it is simpler and more widely used by Python programmers.