NumPy Tutorial NumPy Statistics NumPy References

NumPy - sum() function



The NumPy sum() function is used to compute sum of array elements over a given axis. The function calculates sum of all elements present in the array by default, otherwise over the specified axis.

Syntax

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

Parameters

a Required. Specify an array containing numbers to sum.
axis Optional. Specify axis or axes along which the sum is calculated. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.
dtype Optional. Specify the data type for the returned array. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer.
out Optional. Specify output array for the result. The default is None. If provided, it must have the same shape as output.
keepdims Optional. If this is set to True, the reduced axes are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. With default value, the keepdims will not be passed through to the sum method of sub-classes of ndarray, but any non-default value will be. If the sub-class method does not implement keepdims the exceptions will be raised.
initial Optional. Specify the starting value for the sum.
where Optional. Specify an array of bool to specify which element to include in the sum.

Return Value

Returns 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.

Example: sum of all values

In the example below, sum() function is used to calculate sum of all values present in the array.

import numpy as np
Arr = np.array([[10,20],[30, 40]])

print("Array is:")
print(Arr)

#sum of all values
print("\nSum of values:", np.sum(Arr))

The output of the above code will be:

Array is:
[[10 20]
 [30 40]]

Sum of values: 100

Example: sum() with axis parameter

When axis parameter is provided, sum is calculated over the specified axes. Consider the following example.

import numpy as np
Arr = np.array([[10,20,30],[70,80,90]])

print("Array is:")
print(Arr)

#sum along axis=0
print("\nSum along axis=0")
print(np.sum(Arr, axis=0))

#sum along axis=1
print("\nSum along axis=1")
print(np.sum(Arr, axis=1))

The output of the above code will be:

Array is:
[[10 20 30]
 [70 80 90]]

Sum along axis=0
[ 80 100 120]

Sum along axis=1
[ 60 240]

Example: sum() with dtype parameter

The dtype parameter can be provided to get the result in the desired data type.

import numpy as np
Arr = np.array([[10,20],[80,90]])
print("Array is:")
print(Arr)

#sum along axis=0 with dtype=complex
print("\nSum along axis=0 (dtype=complex)")
print(np.sum(Arr, axis=0, dtype=complex))

The output of the above code will be:

Array is:
[[10 20]
 [80 90]]

Sum along axis=0 (dtype=complex)
[ 90.+0.j 110.+0.j]

Example: sum() with initial parameter

If the initial parameter is provided the sum starts with the specified value.

import numpy as np
Arr = np.array([[5,10],[15,20]])
print("Array is:")
print(Arr)

#sum along axis=0 with initial=100
print("\nSum along axis=0 (initial=100)")
print(np.sum(Arr, axis=0, initial=100))

The output of the above code will be:

Array is:
[[ 5 10]
 [15 20]]

Sum along axis=0 (initial=100)
[120 130]

Example: sum() with where parameter

With where parameter an array of bools can be passed to specify which element to include in the sum.

import numpy as np
Arr = np.array([[5,10,15],[20,25,30]])
whr = np.array([[True,False,True],[False,True,False]])
print("Array is:")
print(Arr)
print("\nArray of bools is:")
print(whr)

#sum along axis=1 with where parameter
print("\nSum along axis=1 with where parameter")
print(np.sum(Arr, axis=1, where=whr))

The output of the above code will be:

Array is:
[[ 5 10 15]
 [20 25 30]]

Array of bools is:
[[ True False  True]
 [False  True False]]

Sum along axis=1 with where parameter
[20 25]

❮ NumPy - Functions