Python:NumPy .sum()
Published Jun 4, 2022Updated May 15, 2024
Contribute to Docs
The .sum() function sums the elements of an array over a given axis.
Syntax
numpy.sum(a, axis, dtype, out, keepdims, initial, where)
The 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 ofarray.out: Anndarrayto 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.initial: The starting value for sum.where: A boolean array that maps toarrayand selects elements to include into the sum.
Example
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]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours