In Python, it’s easy to add one array to another with the built-in Python library NumPy. NumPy is a free Python library equipped with a collection of complex mathematical operations suitable for processing statistical data.
NumPy can be imported into Python as follows:
import numpy as np
To add the two arrays together, we will use the numpy.add(arr1,arr2)
method. In order to use this method, you have to make sure that the two arrays have the same length.
If the lengths of the two arrays are not the same, then broadcast the size of the shorter array by adding zero’s at extra indexes.
Two arrays are added using the np.add()
method in the code below.
import numpy as nparr1 = np.array([3, 2, 1])arr2 = np.array([1, 2, 3])print ("1st array : ", arr1)print ("2nd array : ", arr2)out_arr = np.add(arr1, arr2)print ("added array : ", out_arr)
To add the two arrays together, we can also use the +
operator.
import numpy as np# Element-wise addition between NumPy arraysarr1 = np.array([3, 2, 1])arr2 = np.array([1, 2, 3])out_arr = arr1 + arr2print(out_arr)
If the arrays are not of the same shape, NumPy will try to broadcast them to a common shape before performing the addition.
Free Resources