NumPy sum()
Summary: in this tutorial, you’ll learn how to use the numpy sum()
function to return the sum of all elements in an array.
Introduction to the numpy sum() function
The numpy sum()
function is an aggregate function that takes an array and returns the sum of all elements.
The following example uses the sum()
function to calculate the sum of all elements of a 1-D array:
import numpy as npa = np.array([1, 2, 3])
total = np.sum(a)
print(total)
Code language: Python (python)
Output:
6
Code language: Python (python)
How it works.
First, create a new numpy array that has three numbers 1, 2, and 3:
a = np.array([1, 2, 3])
Code language: Python (python)
Second, calculate the sum of all elements in array a by using the sum()
function:
total = np.sum(a)
Code language: Python (python)
Third, display the result:
print(total)
Code language: Python (python)
The following example uses the sum()
function to calculate the sum of all elements of a 2-D array:
import numpy as npa = np.array([
[1, 2, 3],
[4, 5, 6]
])
total = np.sum(a)
print(total)
Code language: Python (python)
Output:
21
Code language: Python (python)
In this example, the sum()
adds up all the numbers of the array a.
The sum()
function also accepts the axis argument that allows you to return the sum of elements of an axis. For example:
import numpy as npa = np.array([
[1, 2, 3],
[4, 5, 6]
])
total = np.sum(a, axis=0)
print(total)
Code language: Python (python)
Output:
[5 7 9]
Code language: Python (python)
In this example, the sum()
function returns a new array where each element is the sum of elements of the array a
on axis-0.
Similarly, you can sum elements on axis-1 like this:
import numpy as npa = np.array([
[1, 2, 3],
[4, 5, 6]
])
total = np.sum(a, axis=1)
print(total)
Code language: Python (python)
Output:
[ 6 15]
Code language: Python (python)
Summary
- Use the
sum()
function to get the sum of all elements of an array. - Use the axis argument to specify the axis that you want to sum up.