numpy.sum

numpy.sum(a, axis=None, dtype=None, out=None)

Return the sum of array elements over a given axis.

Parameters:

a : array_like

Elements to sum.

axis : integer, optional

Axis over which the sum is taken. By default axis is None, and all elements are summed.

dtype : dtype, optional

The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of a is used. An exception is when a has an integer type with less precision than the default platform integer. In that case, the default platform integer is used instead.

out : ndarray, optional

Array into which the output is placed. By default, a new array is created. If out is given, it must be of the appropriate shape (the shape of a with axis removed, i.e., numpy.delete(a.shape, axis)). Its type is preserved.

Returns:

sum_along_axis : ndarray

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

See also

ndarray.sum
equivalent method

Notes

Arithmetic is modular when using integer types, and no error is raised on overflow.

Examples

>>> np.sum([0.5, 1.5])
2.0
>>> np.sum([0.5, 1.5], dtype=np.int32)
1
>>> np.sum([[0, 1], [0, 5]])
6
>>> np.sum([[0, 1], [0, 5]], axis=1)
array([1, 5])

If the accumulator is too small, overflow occurs:

>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
-128

Previous topic

numpy.prod

Next topic

numpy.nansum

This Page

Quick search