Summary: in this tutorial, you’ll learn how to use the numpy add() function or the + operator to add two equal-sized arrays.
Introduction to the Numpy add() function #
The + or add() function of two equal-sized arrays perform element-wise additions. It returns the sum of two arrays, element-wise.
Let’s take some examples of using the + operator and add() function.
Using NumPy add() function and + operator to add two 1D arrays example #
The following example uses the + operator to add two 1-D arrays:
import numpy as np
a = np.array([1, 2])
b = np.array([2, 3])
c = a + b
print(c)Code language: Python (python)Output:
[3 5]Code language: Python (python)How it works.
First, create two 1D arrays with two numbers in each:
a = np.array([1, 2])
b = np.array([2, 3])Code language: Python (python)Second, add the array a with b and assign the result to the variable c:
c = a + bCode language: Python (python)The + adds each element of array a with the corresponding element in the array b together:
[1+2, 2+4] = [3,5]Code language: Python (python)Similarly, you can use the add() function to add two 1D arrays like this:
import numpy as np
a = np.array([1, 2])
b = np.array([2, 3])
c = np.add(a, b)
print(c)Code language: Python (python)Output:
[3 5]Code language: Python (python)Using NumPy add() function and + operator to add two 2D arrays example #
The following example uses the + operator to add two 2D arrays:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = a + b
print(c)Code language: Python (python)Output:
[[ 6 8]
[10 12]]Code language: Python (python)In this example, the + operator performs element-wise addition like this:
[[ 1+5 2+6]
[3+7 4+8]]Code language: Python (python)Likewise, you can use the add() function to add two 2D arrays:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = np.add(a, b)
print(c)Code language: Python (python)Output:
[[ 6 8]
[10 12]]Code language: Python (python)Summary #
- Use the + operator or
add()function to add two equal-sized array.