📅  最后修改于: 2023-12-03 15:19:14.513000             🧑  作者: Mango
In Python, the numpy.ndarray.__add__()
method is used to perform element-wise addition of two numpy arrays. It returns a new numpy array by adding the corresponding elements of the two input arrays. This method is implemented as a dunder method (__add__
) in the ndarray
class of the NumPy library.
numpy.ndarray.__add__(other)
other
: Another numpy array or a scalar value to be added element-wise with the current array.The method returns a new numpy array containing the element-wise addition of the two input arrays.
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
c = a.__add__(b)
print(c)
Output:
array([ 6, 8, 10, 12])
In the above example, we create two numpy arrays a
and b
. We then use the __add__()
method to add the corresponding elements of a
and b
, resulting in a new numpy array c
. The print()
statement displays the resulting array.
The numpy.ndarray.__add__()
method also supports broadcasting. Broadcasting is a powerful feature in NumPy that allows arrays of different shapes to be added together. The smaller array is "broadcasted" to match the shape of the larger array before performing the addition.
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([10, 20])
c = a.__add__(b)
print(c)
Output:
array([[11, 22],
[13, 24]])
In the above example, we have a 2D array a
and a 1D array b
. The __add__()
method broadcasts b
to match the shape of a
and performs element-wise addition. The resulting array c
is displayed using the print()
statement.
The numpy.ndarray.__add__()
method is a powerful tool for performing element-wise addition of numpy arrays in Python. It not only adds corresponding elements but also supports broadcasting, making it a versatile function for array manipulations.