Numpy sum()
function is used to sum the elements of Numpy array over the provided axis.
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.
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.
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-
When axis=0 is passed to sum() function, then it works like this-
When axis=1 is passed to sum() function, then it works like this-