Adding a Constant to All Elements of a NumPy Array
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
where
arr
is a numpy array.c
is a constant.output
is the resulting numpy array.
Examples
1. Add a constant of 3 to each element in the 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.
Python Program
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)
Output
Summary
In this NumPy Tutorial, we learned how to add a constant to each of the element in numpy array using addition operator.