Python Numpy – Add a constant to all the elements of 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 +. To addition operator, pass array and constant as operands as shown below.

b = a + c
Run

where a is input array and c is a constant. b is the resultant array.

Example

In the following python example, we will add a constant 3 to an array a. The resulting array is stored in b.

import numpy as np

#2D array
a = (np.arange(8)*2).reshape(2,4)

#print array
print("The array\n",a)

#adding a constant to all the elemnets of array
b = a + 3

print("\nAfter adding a constant to all the elemnets of array\n",b)
Run
Python Numpy Array - Add a constant