Numpy – Sum of elements in Array – sum()

Numpy sum()

To get the sum of all elements in a numpy array, you can use Numpy’s built-in function sum().

In this tutorial, we shall learn how to use sum() function in our Python programs.

Syntax – numpy.sum()

The syntax of numpy.sum() is shown below.

numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>)

We shall understand the parameters in the function definition, using below examples.

Example 1: Numpy sum()

In this example, we will find the sum of all elements in a numpy array, and with the default optional parameters to the sum() function.

Python Program

import numpy as np

a = np.array([4, 5, 3, 7])
print('input\n',a)

b = np.sum(a)
print('sum\n',b)
Run

Output

input
 [4 5 3 7]
sum
 19

Explanation

4 + 5 + 3 + 7 = 19

Example 2: Numpy sum() along axis

You can specify axis to the sum() and thus get the sum of the elements along an axis.

Python Program

import numpy as np

a = np.array([4, 5, 3, 7]).reshape(2, 2)
print('input\n',a)

b = np.sum(a, axis=0)
print('sum\n',b)
Run

Output

input
 [[4 5]
 [3 7]]
sum
 [ 7 12]

Explanation

 [[4  5]
   +  +
  [3  7]]
------------
  [7  12]

In the above program, we have found the sum along axis=0. Now, let us try with axis=1.

Python Program

import numpy as np

a = np.array([4, 5, 3, 7]).reshape(2, 2)
print('input\n',a)

b = np.sum(a, axis=1)
print('sum\n',b)
Run

Output

input
 [[4 5]
 [3 7]]
sum
 [ 9 10]

Explanation

[4 + 5] = 9
[3 + 7] = 10

Hence [9 10]

Example 3: Specify an initial value to the sum

You can also specify an initial value to the sum.

By default, the initial value is 0. But, if you specify an initial value, the sum would be initial value + sum(array) along axis or total, as per the arguments.

Python Program

import numpy as np

a = np.array([4, 5, 3, 7])
print('input\n',a)

b = np.sum(a, initial=52)
print('sum\n',b)
Run

Output

input
 [4 5 3 7]
sum
 71

Explanation

sum(a, initial=52) = sum(a) + initial
                   = sum([4 5 3 7]) + 52
                   = 19 + 52
                   = 71   

Summary

In this Numpy Tutorial of Python Examples, we learned how to get the sum of elements in numpy array, or along an axis using numpy.sum().