How to add one array to another array in Python

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.

svg viewer

Library

NumPy can be imported into Python as follows:

import numpy as np

Method 1

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.

Code

Two arrays are added using the np.add() method in the code below.

import numpy as np
arr1 = 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)

Method 2

To add the two arrays together, we can also use the + operator.

import numpy as np
# Element-wise addition between NumPy arrays
arr1 = np.array([3, 2, 1])
arr2 = np.array([1, 2, 3])
out_arr = arr1 + arr2
print(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

Copyright ©2024 Educative, Inc. All rights reserved