Numpy sum() in Python | np sum() in Python

Numpy sum() function is used to sum the elements of Numpy array over the provided axis.

Syntax of Numpy sum()

np.sum(a, axis=None, dtype=None)

a parameter is used to specify the array upon which we have to perform sum() function.

axis parameter is optional and is used to specify the axis along which we want to perform addition. When you do not provide axis parameter value to np.sum() function then it adds all the values together and produces a single value.

dtype parameter controls the data type of the resultant sum.

Python program using np.sum() on 1-Dimensional Numpy Array

import numpy as np

a = np.array([32, 4, 8, 12, 20])
print('Sum of arr is ', np.sum(a))

Output of the above program

Sum of arr is 76

As you can see in the above output, np.sum() has added all the values. In 1-dimensional array, it is optional to provide axis parameter to sum() function.

Numpy sum on 1-Dimensional Array

Python program using np.sum() on 2-Dimensional Numpy Array

import numpy as np

a = np.array([[32, 4, 8, 12, 20], [35, 5, 15, 10, 30]])
print('Sum of arr is ', np.sum(a))
print('Sum of arr along axis0 is ', np.sum(a, axis=0))
print('Sum of arr along axis1 is ', np.sum(a, axis=1))

Output of the above program

Sum of arr is  171
Sum of arr along axis0 is  [67  9 23 22 50]
Sum of arr along axis1 is  [76 95]

When axis value is not provided, then sum() function works like this-

Numpy sum on 2-Dimensional Array

When axis=0 is passed to sum() function, then it works like this-

Numpy sum on 2-Dimensional Array with axis0

When axis=1 is passed to sum() function, then it works like this-

Numpy sum on 2-Dimensional Array with axis1

Recommended Posts