Skip to content
LearnPY
NumPyfunction reference

np.sum

Add values across an array or along one axis.

Signature

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

What it does

np.sum reduces an array to a total. Without an axis it sums every element. With an axis it collapses that axis and keeps the others, unless keepdims asks for a length-one dimension instead.

Parameters

aarray_like
The values to add.
axisint or tuple of ints, optionaloptional
The axis or axes to collapse.
keepdimsbool, optionaloptional
Keep collapsed axes as length-one dimensions.

Returns

ndarray or scalar

Example

pythonnp.sum example
import numpy as np

grid = np.array([[1, 2, 3], [4, 5, 6]])
print(grid.sum(axis=0))
print(grid.sum(axis=1))

Output

[5 7 9]
[ 6 15]

Watch out for

  • Axis 0 collapses rows, so the result has one value per column.
  • Integer sums can overflow a small dtype; specify dtype when needed.