Dividing All Elements in a NumPy Array by a Constant


NumPy - Divide all elements in array by a constant

Dividing a NumPy array by a constant is as easy as dividing two numbers. To divide each and every element of an array by a constant, use division arithmetic operator /. Pass array and constant as operands to the division operator as shown below.

b = a / c

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

Examples

1. Divide all the elements in the numpy array by 3

In the following python example, we take an array in a, and divide this array by a constant 3. The resulting array is stored in b, and print to the standard output.

Python Program

import numpy as np

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

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

#divide all the elements of array by constant
b = a / 3

print("\nAfter dividing by a constant\n",b)

Output

Summary

In this NumPy Tutorial, we learned how to divide elements in a numpy array by a constant.