.sum() function sums the elements of an array over a given axis.
numpy.sum(a, axis, dtype, out, keepdims, initial, where)
a argument is required and represents the array of elements to sum. All other arguments are optional. Used by itself,
a will result in a scalar that sums all the elements of the array.
.sum() provides the following arguments:
a: The array of elements to sum.
axis: An int or tuple of ints specifying the axis/axes along which to sum.
dtype: The type of the returned array and the accumulator used to sum elements. Defaults to the dtype of
ndarrayto receive result. Must have the same shape as expected output.
keepdims: A boolean if true will keep reduced axes in the result as dimensions with size one.
inital: The starting value for sum.
where: A boolean array that maps to
arrayand selects elements to include into the sum.
The following example creates an array then uses a few
.sum() operations to sum the elements.
import numpy as npnd = np.array([[1,2,3],[4,5,6]])print(np.sum(nd))print(np.sum(nd, axis=0))print(np.sum(nd, axis=1))
This produces the following output:
21[5 7 9][ 6 15]