Numpy Array – Add a constant to all elements of the array
Adding a constant to a NumPy array is as easy as adding two numbers.
To add a constant to each and every element of an array, use addition arithmetic operator
+. Pass array and constant as operands to the addition operator as shown below.
output = arr + c
arris a numpy array.
cis a constant.
outputis the resulting numpy array.
In the following python example, we will add a constant
3 to an array
arr. The resulting array is stored in
output and print to the standard output.
import numpy as np #2D array arr = (np.arange(8)*2).reshape(2,4) #print array print("The array\n", arr) #adding a constant to all the elemnets of array output = arr + 3 print("\nAfter adding a constant to all the elemnets of array\n", output)
In this Numpy Tutorial of Python Examples, we learned how to add a constant to each of the element in numpy array using addition operator.